Azerty123 Azerty123 - 4 years ago 277
C# Question

Circular Dependency and Unity Container

I have a solution :

solution


  • Business
    have a reference to
    Business.Interfaces
    ,
    DataAccess.Interfaces
    and
    Factory
    (for resolve
    IDataAccess
    in
    DataAccess.Interfaces
    )

  • MainProject
    have a reference to
    Business.Interfaces
    and
    Factory
    (for resolve
    IBusiness
    in
    Business.Interfaces
    )



My factory project use
Unity
for resolve dependencies. This project must have a reference to all others project except
MainProject
to access to constructors of concrete class and do mapping between class and interfaces.

But I don't add a reference to
Business
in
Factory
project because visual studio says me :

A reference to Business could not be added. Adding this project as a reference would cause a circular dependency

How to resolve this ?

Answer Source

As @Andrei pointed out, when configuring an application to use DI, the application should be responsible for wiring up all of its dependencies in its Composition Root.

A Composition Root is a (preferably) unique location in an application where modules are composed together.

Furthermore, the composition root should not be moved to an external library. Think of the composition root as a modern replacement for a .config file. It is the application that is responsible for loading it and providing its contents to the dependent assemblies - the same is true for the Composition Root.

It is the Composition Root's job to push the dependencies down into the rest of the application. The dependent assemblies should not try to pull their own dependencies. It's called the Hollywood principle - "Don't call us, we'll call you". That said, it is also common to use the abstract factory pattern in conjunction with DI.

See this answer for a good visual representation of how it should work. Your application looks a lot like the first image - you should aim to make it like the second one. The application is logically setup in separate layers that depend on each other, but it is physically very flat.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download