resolving circular dependencies with dependency injection [closed]

孤街浪徒 提交于 2019-11-29 02:52:31

问题


I've seen several articles on various websites that propose resolving circular dependencies between .NET assemblies by using dependency injection. This may resolve the build errors but it's not really resolving the circular dependency, is it? To me, there seems to still be a logical error in the architecture. Am I crazy or do others agree 1) this is a less than stellar use of DI, and 2) not the appropriate way to solve circular dependency issues?


回答1:


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/




回答2:


  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:

  • business-logic-layer-and-data-access-layer-circular-dependency
  • are-circular-class-dependencies-bad-from-a-coding-style-point-of-view

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




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/1450997/resolving-circular-dependencies-with-dependency-injection

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