views:

646

answers:

4

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?

+4  A: 

I agree with you. The first step in solving a circular dependency should be to look for errors in the architecture.

AdamRalph
+1  A: 

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

Juri
+6  A: 

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/

Andrei Vajna II
+1  A: 
  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.

Cohen