每个类库的依赖注入容器 [英] Dependency Injection Container for each Class Library

查看:136
本文介绍了每个类库的依赖注入容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是我第一次与DI打交道,如果我误解了整个DI的内容,请纠正我.

So, this is the first time I'm dealing with DI, please correct me if I misunderstood the whole DI thingy.

这些是我的几个项目:

  1. Web应用程序/Web API项目-取决于服务类+注入自动映射器(仅适用于当前项目的配置)
  2. 服务(类库)-取决于数据类+注入自动映射器(配置仅适用于当前项目)
  3. 数据(类库)

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

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.

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

I have read some of the article, showing that it cannot be done (not sure if i interpret them correctly) but I'm not sure why?

如果无法完成 ,任何人都可以解释一下,以及如何实现此目的,并且我不想在应用程序层DI的数据层中注册类.

If it cannot be done, can anyone explain it and how can I achieve this and I doesn't want to register the classes in Data Layer in the Application Layer DI.

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

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

推荐答案

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

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.

此处所述,您应该组成所有对象图:

As explained here, you should compose all object graphs:

尽可能靠近应用程序的入口点.

此地方称为组成根:

组合根是应用程序中将模块组合在一起的(最好)唯一位置.

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

In other words, the only place that you should use your DI container and configure your application's dependencies is in the start-up project. All other projects should be oblivious to the container and should purely apply Constructor Injection.

我已经阅读了一些文章,表明无法完成

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

可以做到,但你不应该这样做.

It can be done, but you shouldn't.

如果每个项目都可以有自己的DI,那么在将IMapper注册为实例时,它将覆盖其他层的IMapper吗?

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

如果您应用组成根模式,此问题将消失.在组成根中,您可以完全控制哪个组件获得哪个依赖项.

This problem goes away if you apply the Composition Root pattern. In the Composition Root you have full control over which component gets which dependency.

专业提示:阅读这本书.

这篇关于每个类库的依赖注入容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆