Custom ModelBinder Lifecycle and Dependency Injection [duplicate]

冷暖自知 提交于 2019-12-11 12:57:51

问题


Possible Duplicate:
Inject a dependency into a custom model binder and using InRequestScope using Ninject

I'm trying to bind an NHibernate session to a custom model binder:

Since a custom model binder appears to be a singleton, I think I need to be concerned with thread safety. This is my current IoC code:

kernel.Bind<ISession>().ToProvider<SessionProvider>().InRequestScope()
    .OnActivation(x => ServiceModelBinder.Service = kernel.Get<IServiceService>());

In my binder, I have the static service field decorated with the ThreadStatic attribute, in an effort to avoid concurrency problems with the session.

Is this even a good idea?

Is there a better way to inject a per request scoped object into a view model? Or should I just not worry about how ugly it looks on paper and just grab the current session from the DependencyResolver where needed?


回答1:


Stay well away from ThreadStaticAttribute in ASP.NET - the only correct way is to put stuff in HttpContext.Items, but there always many better approaches to be tried before you go to something low level like that.

Key problem here is that you are working with a bad assumption - model binders are shared between requests.



来源:https://stackoverflow.com/questions/12757112/custom-modelbinder-lifecycle-and-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!