自定义ModelBinder生命周期和依赖注入 [英] Custom ModelBinder Lifecycle and Dependency Injection
问题描述
Possible Duplicate:
Inject a dependency into a custom model binder and using InRequestScope using Ninject
我正在尝试将NHibernate会话绑定到自定义模型绑定程序:
I'm trying to bind an NHibernate session to a custom model binder:
由于自定义模型活页夹似乎是一个单例,因此我认为我需要关注线程安全性.这是我当前的IoC代码:
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>());
在我的活页夹中,我的静态服务字段装饰有ThreadStatic
属性,目的是避免会话的并发问题.
In my binder, I have the static service field decorated with the ThreadStatic
attribute, in an effort to avoid concurrency problems with the session.
这是个好主意吗?
是否有更好的方法将按请求范围的对象注入视图模型?还是我不应该担心它在纸面上看起来多么丑陋,并在需要的地方从DependencyResolver
抓取当前会话?
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?
推荐答案
远离ASP.NET中的ThreadStaticAttribute-唯一正确的方法是将内容放入HttpContext.Items
中,但是在此之前总是有许多更好的方法可以尝试你去
像这样低级的东西.
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.
这篇关于自定义ModelBinder生命周期和依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!