How to inject dependencies per http request (or pe

2019-08-07 09:13发布

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?

1条回答
该账号已被封号
2楼-- · 2019-08-07 09:46

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

查看更多
登录 后发表回答