将服务注入另一种服务的最佳实践 [英] Best practice injecting service into another service

查看:47
本文介绍了将服务注入另一种服务的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设我有两个实体( 订阅 应用 ),每个实体都有他的存储库层分别命名为( SubscriptionRepository ApplicationRepository ),并且每个都有两个服务( ISubscriptionService IApplicationService )

We suppose that I have Two Entity (Subscription and Application) and for each one his Repository layer named (SubscriptionRepository and ApplicationRepository) and two Service for each one (ISubscriptionService and IApplicationService)

在某些情况下,假设我们最终遇到 ApplicationService需要注入SubscriptionService的情况 SubscriptionService需要注入ApplicationService的情况(相反),并且当然是 循环依赖

In some case, suppose we end up with a case where ApplicationService need to inject SubscriptionService and a case where SubscriptionService need to inject ApplicationService ( the reverse) and and of course it Is a Circular Dependency

我的问题是:

当我想将服务注入另一种方式时,我应该如何思考而不会陷入此类问题.(这意味着我如何确定是否需要将ApplicationService注入SubscriptionService或相反)?

When I want to inject service into another how I should reflect to not fall into this type of problem. (it means how i can decide if i need to inject ApplicationService into SubscriptionService or the reverse)?

推荐答案

您可以通过使两个服务都依赖于另一个抽象来使两个服务的依赖关系相互转化.在您的情况下,由于两者都是域服务,因此由您的实体或域服务发出的 域事件 可能很合适.

You could invert the dependencies of both services to each other by making both depend on another abstraction instead. In your case, as both are domain services, domain events emitted by either your entities or the domain services could be a good fit.

但是在不了解有关您的域以及 Application Subscription 专用的更多详细信息的情况下,很难确定您是否没有遇到设计问题.

But without knowing more details about your domain and what Application and Subscription are dedicated for it is hard to tell if you are not facing a design problem.

如果 如果您认为存在设计缺陷,建议我向自己问这些问题,这些问题通常在我不确定我是否在自己的设计中确定了正确的界限时会有所帮助域模型.

If you think there is a design flaw I suggest to ask yourself these questions which often help me when I am not sure if I have drawn the correct boundaries in my domain model.

  • 合并这两个相互依赖的组件是否更有意义?
  • 我的组件A 是否访问了组件B 的某些功能,而该功能应该是组件A 的一部分?
  • 我的组件B 是否访问了组件A 的某些功能,而该功能应该是组件B 的一部分?
  • 由另一个访问的A或B的功能应该在第三个尚未发现的组件中吗?这可能是另一个界面,域事件或类似的东西...
  • Would it make more sense to merge these two components which are dependent on each other?
  • Does my component A access some feature of component B which should rather be part of component A?
  • Does my component B access some feature of component A which should rather be part of component B?
  • Should functionality of A or B which are accessed by the other rather be in a third not yet discovered component? This could be another interface, domain events or something similar...

这篇关于将服务注入另一种服务的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆