Custom ModelBinder Lifecycle and Dependency Injection [duplicate]
Asked Answered
M

1

1

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?

Myna answered 6/10, 2012 at 5:45 Comment(1)
see also related link on that postMita
M
2

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.

Mita answered 8/10, 2012 at 13:7 Comment(3)
"Model binders are shared between requests." That is my assumption, actually. Can you explain what's wrong with my actual assumption? Is a request not necessarily handled by a single thread?Myna
Anyhow, thanks for pointing me back at that answer. The solution is much nicer, it's just a bit confusing for an IoC noob because it's a little too simple :)Myna
@mootinator The processing of a request can move from thread to thread. Generally only when doing async stuff, but not always. To be honest the fact that you were trying to do both thread and request scoping on something that is neither didnt make it clear to me in the slightest that you were aware that it was neither. Its not clear to me which assumption you're referring to as the key one. Its only now I see you're using ThreadLocal on the static. To be honest there's nothing jumping out as wrong, just everything as there's a kitchen sink of concepts...Mita

© 2022 - 2024 — McMap. All rights reserved.