干净的架构和实体的依赖注入

发布于 2025-01-09 17:01:31 字数 81 浏览 0 评论 0原文

考虑到清洁架构的域,实体是否可以通过依赖项注入接收外部对象以验证其字段?这是可以接受的吗?目前我认为不可以,因为尽管有抽象,但它似乎违反了依赖规则。

Considering the Clean Architecture's domain, does the entities can receive an external object trough a dependency injection to validate it's fields? This is acceptable? At this moment I think no, because it seems breaking the dependency rule despite the abstrations.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巴黎夜雨 2025-01-16 17:01:31

您可以将验证器注入到实体中,并且仍然遵守依赖关系规则。您只需指定一个接口,

public interface OrderValidator {
    public void validate(Order order)
    // maybe more fine grained methods
}

在外层(网关)中实现它

public MyOrderValidator implements OrderValidator {
   // ...
}

并将其传递给实体。

public class Order {
  
    public Order(OrderValidator v){
       // save to private field
    }
}

但是这种设计意味着您从实体中提取验证逻辑并将其放在其他地方。这会导致贫乏的域模型

通常,域实体包含确保其状态所需的验证规则。

如果您的验证规则属于多个实体(例如 DDD 中的聚合),则应使用域服务。当您想要将依赖项注入域实体时,必须在创建实体时注入它。您通常通过简单地调用实体的构造函数来在用例中创建实体。用例传递依赖项,或者您创建一个负责注入依赖项的工厂。但存储库也返回实体,并且还必须注入依赖项。使用工厂时,存储库也可以使用工厂。

最后,在域服务中注入依赖项并让域服务进行验证也可能更容易。但正如我上面所说:这很容易导致贫血模型,您应该始终尽力防止这种情况发生。

You can inject a validator into an entity and still honor the dependency rule. You just have to specify an interface,

public interface OrderValidator {
    public void validate(Order order)
    // maybe more fine grained methods
}

implement it in an outer layer (gateways)

public MyOrderValidator implements OrderValidator {
   // ...
}

and pass it to the entity.

public class Order {
  
    public Order(OrderValidator v){
       // save to private field
    }
}

BUT this design means that you pull validation logic out of the entity and you put it somewhere else. This leads to an anemic domain model.

Usually a domain entity contains the validation rules it needs to ensure it's state.

If you have validation rules that belong to multiple entities, like an aggregate in DDD, you should use a domain service. When you want to inject a dependency into a domain entity it must be injected whenever an entity is created. You usually create entities within use cases by simply calling their constructor. Either the use case passes the dependency or you create a factory that is responsible for injecting dependencies. But also repositories return entities and also must inject the dependencies. When using a factory the repositories can use the factory as well.

Finally it might also be easier to inject a dependency in a domain service and let the domain service do the validation. But as I said above: This can easily lead to an anemic model and you should always try to prevent this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文