Can dependency injection prevent a circular dependency?-Collection of common programming errors
You probably could solve this with DI, but you shouldn’t.
If I understand correctly, you have something like this:
+ Assembly A + Assembly B | | +-- Interface IFoo +-- Class ConcreteFoo : IFoo | ^ +-- Class MyClass -->------->-------|
In other words, you’re trying to get MyClass to reference ConcreteFoo, but you can’t because assembly B, which ConcreteFoo resides in, already depends on IFoo in A.
This is a design error. If you declare the interface IFoo in Assembly A, but no concrete implementations, then any other interfaces/classes in assembly A should only reference IFoo, never a concrete class that implements it.
There are three ways to eliminate the circular dependency:
-
Make
MyClassdependent onIFooinstead ofConcreteFoo. This is probably the best option if you can do it. If the issue is that you need a physical instance ofIFoofor use inMyClassand don’t know where to get one from, then have it take anIFooin the constructor – let whoever usesMyClassfigure out whatIFooto use. -
Move the interfaces to their own assembly. This is still a reasonably good practice. Your design will look like this:
+ Assembly App + Assembly Interfaces + Assembly Concrete
| | |
| +-- Interface IFoo |
| | \ |
+-- Class MyClass | \------+-- Class ConcreteFoo
| | | ^
+---- Member Foo ->--------------------->-------------------|
- Move
MyClassto its own assembly. Effectively your dependency tree will look the same as in #2 above, but if assemblyAis much smaller thanBthen this would require less effort.
Hope that helps.