Ioc / DI-为什么我必须引用应用程序入口点中的所有层/程序集? [英] Ioc/DI - Why do I have to reference all layers/assemblies in application's entry point?

查看:60
本文介绍了Ioc / DI-为什么我必须引用应用程序入口点中的所有层/程序集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(与此问题相关,,依赖关系图严重展平





如绿色所示,现在可以重用 Library C 而不用拖拽任何不必要的依赖项。



但是,在许多DI容器中,您都不会必须将硬引用添加到所有必需的库。相反,您可以以基于约定的程序集扫描(首选)或XML配置的形式使用 late绑定



但是,您必须记住将程序集复制到应用程序的bin文件夹中,因为这不再自动发生。就个人而言,我很少觉得值得付出额外的努力。



有关此答案的更详细的版本,请参见此摘录来自我的书依赖性注入,原理,实践,模式


(Related to this question, EF4: Why does proxy creation have to be enabled when lazy loading is enabled?).

I'm new to DI, so bear with me. I understand that the container is in charge of instantiating all of my registered types but in order to do so it requires a reference to all of the DLLs in my solution and their references.

If I weren't using a DI container, I wouldn't have to reference the EntityFramework library in my MVC3 app, only my business layer, which would reference my DAL/Repo layer.

I know that at the end of the day all DLLs are included in the bin folder but my problem is having to reference it explicitly via "add reference" in VS in order to be able to publish a WAP with all necessary files.

解决方案

If I wasn't using a DI container, I wouldn't have to reference EntityFramework library in my MVC3 app, only my business layer which would reference my DAL/Repo layer.

Yes, that's exactly the situation DI works so hard to avoid :)

With tightly coupled code, each library may only have a few references, but these again have other references, creating a deep graph of dependencies, like this:

Because the dependency graph is deep, it means that most libraries drag along a lot of other dependencies - e.g. in the diagram, Library C drags along Library H, Library E, Library J, Library M, Library K and Library N. This makes it harder to reuse each library independently from the rest - for example in unit testing.

However, in a loosely coupled application, by moving all the references to the Composition Root, the dependency graph is severely flattened:

As illustrated by the green color, it's now possible to reuse Library C without dragging along any unwanted dependencies.

However, all that said, with many DI Containers, you don't have to add hard references to all required libraries. Instead, you can use late binding either in the form of convention-based assembly-scanning (preferred) or XML configuration.

When you do that, however, you must remember to copy the assemblies to the application's bin folder, because that no longer happens automatically. Personally, I rarely find it worth that extra effort.

A more elaborate version of this answer can be found in this excerpt from my book Dependency Injection, Principles, Practices, Patterns.

这篇关于Ioc / DI-为什么我必须引用应用程序入口点中的所有层/程序集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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