How to avoid Cyclic Dependencies when using Dependency Injection?

我们两清 提交于 2019-12-24 06:13:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/49472886/how-to-avoid-cyclic-dependencies-when-using-dependency-injection

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