Leonz
Leonz

Reputation: 141

How to avoid Cyclic Dependencies when using Dependency Injection?

I am relatively new to the concept dependency injection, so I am unsure about how it prevents cyclic dependencies. Let's say I have followed projects (the sample project structure might not be good but please bear with me)

Project A:

  • Domain Layer
  • IRepository

Project B:

  • RepositoryImpl --> implement IRepository interface

In this case Project B will need to reference Project A. But to set up Project A, let's say Unity Container, Project A will need to reference Project B in order to have something like this in the Unity Config.

container.RegisterType<IRepository, Repository>();

But doesn't this introduce cyclic dependency? Or is it I'm having wrong understanding in either Dependency Injection or cyclic Dependency? or even both?

Upvotes: 1

Views: 605

Answers (1)

Steven
Steven

Reputation: 172606

You are missing an important concept here, which is the concept of the Composition Root. The best and most elaborate description of what a Composition Root is, can be found here. To summarize:

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

As the article explains:

Most classes use Constructor Injection. By doing this they push the responsibility of the creation of their dependencies up to their consumer. That consumer -again- push the responsibility of the creation of its dependencies up as well.

We can’t delay the creation of our classes indefinitely. There must be a location where we create our object graphs. You should concentrate this creation into a single area of your application. This place is called the Composition Root.

Only the application's entry point contains a Composition Root, any other libraries in application do not.

This means that the Domain Layer itself does not register its types into the DI Container—only the startup project does this. When you do this, the Domain Layer will therefore not have to depend the Data Access Library (your Project B).

Both the first edition (chapter 2) and second edition (chapter 3) of the book Dependency Injection in .NET contain a elaborate discussion of an example that is very close to the application structure given in your question. The previously referenced Composition Root article is an excerpt from the second edition. The first chapter can be read for free online.

Upvotes: 2

Related Questions