开发者

How to inject dependencies per http request (or per http context) with unity 2.0 and asp.net mvc

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?


Try http://mvcunity.codeplex.com/ or download the source code to see how it's done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜