如何使用 unity 2.0 和 asp.net mvc 为每个 http 请求(或每个 http 上下文)注入依赖项
我已经阅读了很多这方面的信息,但我找不到任何最新的信息(截至 2011 年 1 月),说明现在应该如何完成此操作。我读过几篇似乎有答案的好文章,但没有详细信息。 unity-2 之前的旧方法主要创建自定义生命周期管理器。现在看来最好的方法是使用在以下位置创建的子容器使用容器管理的生命周期在请求开始时并在请求结束时进行处置。另一个人说他们已经使用 createchildcontainer 的分层生命周期实现了这一点。
我发现的大多数材料都说要在 Application_BeginRequest 期间创建子容器,我已经尝试过了。这不起作用,因为我的控制器工厂(来自 MvcContrib 的 IoCControllerFactory)使用在 Application_Start 期间注册的容器(MvcContrib 中 IDependencyResolver 的实现),这是默认/根容器。
我在 web.config 中进行了统一设置,并且可以创建子容器,但我似乎无法让任何控制器将它们用于 DI 来根据请求创建单例。我是否需要创建一个特殊的容器来在控制器工厂中使用,而不是根容器?它应该是容器管理的还是分层的?我不应该在每个请求上重新设置 DependencyResolver,不是吗?
I've read a lot of info on this, but I can't find anything current (as of 1/2011) as to how exactly this should be done nowadays. I've read a couple of good posts that seem to have the answer, without the details. Older pre-unity-2 approaches mostly created custom lifetime managers. It appears the best way to do it now is to use a child container that is created at the beginning of the request and disposed at the end of the request, using container-managed lifetime. Another person said they've achieved this using hierarchical lifetime with createchildcontainer.
Most of the material I found says to create the child container during Application_BeginRequest, which I've tried. That doesn't work because my controller factory (IoCControllerFactory from MvcContrib) uses the container registered during Application_Start (an implementation of IDependencyResolver in MvcContrib), which is the default/root container.
I have my unity setup in web.config, and I can create child containers, but I can't seem to get any controllers to use them for DI to create singletons per request. Do I need to create a special container to use in the controller factory, instead of the root? Should it be container-managed or hierarchical? I shouldn't be re-setting the DependencyResolver on every request, should I?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试 http://mvcunity.codeplex.com/ 或下载源代码看看它是如何完成的。
Try http://mvcunity.codeplex.com/ or download the source code to see how it's done.