resolving circular dependencies with dependency injection [closed]

坚强是说给别人听的谎言 提交于 2019-11-30 05:21:30

If you have circular dependencies between two objects, it means you need a third object, on which the two objects will depend on, so they won't depend on each other. Here is an article that is the exact solution to your problem:

http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/

Cohen
  1. Yes, you make it even harder to detect them by using an extra layer of abstraction.
  2. You absolutely do not solve the circular dependency but hide it by adding an extra layer of abstraction, using late bounding, or/and loosely coupling it.

The same answer returns in the following posts (which I will add for references) which is create a 3rd class on which both depend. This translates to: you are violating the Single Responsibility Principle. By moving (extracting) the responsibility both classes depend on in a separate class you'll remove the circular dependency.

FYI the Single Responsibility Pattern on Wikipedia

StackOverflow discussions by others:

My answer on StackOverflow with an example of extracting the responsibility in a seperate class.

DI is not for circular dependency resolution but rather for facilitating the creation of nicely decoupled components and thus more testable ones.

I'll toss in my $0.02 here since I found this helpful post by searching for "removing cyclical dependencies"

Yes. You can use DI to resolve circular dependencies. The first step to fixing any issue is finding it. Ninject complained about my circular dependency and threw a helpful exception at bootstrapping. Ninject found it for me and is forcing me to fix it. I could cheat and use property injection or method injection but that breaks my protection of class invariants (which is I think what you are complaining about).

So a vote for ctor injection via IoC because it will spot circular dependencies for you. It is then up to you to refactor and remove the architectural bug.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!