In my MVC3 project I've setup my kernel to Ninject the Entityframework context on a InRequestScope
basis, this works perfect. But I have a background runner that does some workflow management.
It fires up a new thread each 5 minutes and I Ninject my dependencies into this thread, If I change the scope to InThreadScope
the Dispose method is fired, but If I change it back to InRequestScope
the Dispose method won't fire.
Is there a way of fallbacking to InThreadScope
if InRequestScope
isn't available?
Update: Just got an upvote for this question and why not update it with some additional info. I think that Ninjects way of handling life time is a bit outdated. Other IoC's have child containers were Transient registered objects live during the whole child container and are disposed when the child containers are. This is a much easier way of combining for example Web API with a custom worker like above scenario.
There's an InScope
method, with which you can specify a custom scoping rule.
The implementation of InRequestScope is currently undergoing change from 2.2-2.4.
So go to the source of your version, look at the impl of InRequestScope
and InThreadScope
and create an amalgam (which you can then slot in as an extension method alongside the other InXXXScope
methods.
It'll look (before you extract it into an extension method) something like:
Bind<X>.To<T>().InScope( ctx => ScopeContext.Request(ctx) ?? ScopeContext.Thread(ctx))
The other way is to create two Bind
ings, with an appropriate constraint such as WhenInjectedInto<T>
to customize the scoping based on the contextual binding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With