问题描述
我有两个相关的(这个问题)的项目,以及其他一些解决方案;
I have a solution with two relevant (to this question) projects, and a few others;
- 类库与其他几个项目使用的功能。
- ASP.NET MVC应用程序。
我的问题基本上是在那里我应该做的IoC和Ninject 2,考虑...
My question is basically where I should do IoC with Ninject 2, considering...
- 类库需要一些迪爱生,其中用于需要Web请求特定的会话对象(想想工作单位)信息库类的其他东西。
- 的MVC应用程序需要DI自从与Ninject 2,你基本上从NinjectHttpApplication继承。
- 的类库单元测试必须意识到这一点注入一组不同的库。
- 单元测试需要注射出于同样的原因。
对于Web应用程序
我自己画成一个角落的精神在这里,因为我只看到三个选项开始。 DI类库中,DI在Web应用程序,或两者兼而有之,但也有与每个问题:
I have painted myself into a mental corner here, because I only saw three options to begin with. DI in the class library, DI in the web app, or both, but there are problems with each:
- 我不能在类库因为MVC应用程序需要从NinjectHttpApplication继承开始与做DI的只有的
- 我不仅可以在MVC应用程序做DI - 类库被其他库使用,毕竟,和MVC应用程序不应该知道太多关于图书馆的内部反正 。
- 我想这是出于我能看到的唯一途径:独立的IoC为这两个项目。类库和MVC应用程序都有自己的IoC设置和做DI为自己的东西,而没有真正关心对方。
有没有人对如何做这样的事情有些最佳做法或准则?我无法想象我在这种情况下,结束了第一人称,它会肯定是很好,知道什么是正确的方式做,这是...
Does anyone have some "best practices" or guidelines on how to do something like this? I can't imagine I'm the first person to end up in this situation, and it would sure be nice to know what the "proper" way to do this is...
谢谢!
推荐答案
我不知道NInject,但除非它比温莎千差万别,StructureMap等答案倾向于保持不变,因为有一些共同的DI图案。考虑到这一点:
I don't know NInject, but unless it works vastly different than Windsor, StructureMap etc. the answers tend to stay the same, as there are some common DI patterns. With that in mind:
要实现的第一件事是,DI是不依赖于诸如NInject或温莎一个特定的框架。它是一组技术和设计模式遵循。你可以使用手动所谓穷人的DI DI,但显然它得到了DI容器。
The first thing to realize is that DI isn't tied to a particular framework such as NInject or Windsor. It is a set of techniques and design patterns to follow. You can do DI manually using so-called Poor Man's DI, but obviously it gets much better with a DI Container.
这是为什么有关?这是相关的,因为一旦你意识到这一点,必然结果是,绝大多数的应用程序的code应具备的没有的的DI容器知识保证责任。
Why is this relevant? It is relevant because once you realize this, the corollary is that the vast majority of your application's code should have no knowledge of the DI Container whatsover.
那么,你使用的DI容器?它应该只在构成根,而你的情况将对应于Global.asax中使用。你可以阅读更多关于这个在this SO回答 - 尽管这问题是关于温莎,原理是一样的。
So where do you use the DI Container? It should only be used in a Composition Root, which in your case would correspond to Global.asax. You can read a bit more about this in this SO answer - although that question is about Windsor, the principle remains the same.
如何单元测试呢?他们应该是完全昧DI容器为好。请参见了解更多详情。
How about your unit tests then? They should be completely ignorant of the DI Container as well. See this other SO answer for more details.
DI可以在图书馆用大量使用构造器注入的来实现。你不需要引用任何DI容器要做到这一点,但如果你使用一个DI容器从成分根解决所有依赖它使生活变得更加简单。
DI can be achieved in your library with copious use of Constructor Injection. You don't need to reference any DI Container to do that, but it makes life a lot easier if you use a DI Container to resolve all dependencies from the Composition Root.
这篇关于我应该在哪里做注射Ninject 2+(和我怎么安排我的模块?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!