每个 Class 库的依赖注入容器

Dependency Injection Container for each Class Library

所以,这是我第一次和DI打交道,如果我对整个DI的理解有误,请纠正我。

这些是我的几个项目:

  1. Web 应用程序/Web API 项目 - 取决于服务 Class + 注入 Automapper(配置仅适用于当前项目)
  2. 服务(Class 库)- 取决于数据 Class + 注入 Automapper(配置仅适用于当前项目)
  3. 数据(Class图书馆)

我的意图是让每个项目都有自己的 DI 容器(说 Unity DI)。我不确定每个项目都可以有自己的 DI 容器。

我已经阅读了一些文章,表明它无法完成(不确定我是否正确解释了它们)但我不确定为什么?

如果无法完成,谁能解释一下,我该如何实现,我不想在数据层中注册类应用层DI。

如果每个项目可以有自己的DI,注册IMapper实例时会覆盖其他层的IMapper吗?

My intention was to have each project having its own DI container (says Unity DI). I'm not sure that each project can have its own DI container.

here所述,您应该组合所有对象图:

As close as possible to the application's entry point.

这个地方叫做合成根:

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

换句话说,您唯一应该使用 DI 容器并配置应用程序依赖项的地方是在启动项目中。所有其他项目都应该忽略容器并且应该纯粹应用 构造函数注入.

I have read some of the article, showing that it cannot be done

可以做到,但不应该。

If each project can have its own DI, when registering the IMapper as instance will it override IMapper of other layers?

如果您应用 Composition Root 模式,这个问题就会消失。在 Composition Root 中,您可以完全控制哪个组件获得哪个依赖项。

专业提示:阅读this book