Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top