Using RegisterPerWebRequest outside the context of a HTTP request

Dec 11, 2012 at 3:16 PM

Now, if you registred service in web request scope you can't create an instance out of HTTP context. May be it makes sense to create instance in transient scope in this case? (similar behavor in Ninject)

My problem: I would like to register my service context in web request scope in APP_START method (asp.net mvc app). I do it:

container.RegisterPerWebRequest<IMyContext, MyContext>();

But I also would like to create IMyContext instance in Task manager that works in out of HTTP context. Now I receive the exception.

What the best solution in this case?

Coordinator
Dec 11, 2012 at 4:01 PM

Previous versions of the Simple Injector returned a transient object when no HTTP context was available. This behavior was 'borrowed' from Autofac and Ninject. Over time however, I found out that this behavior did not comply with the design principles behind Simple Injector (developers got bitten by this behavior). This behavior makes it very easy to let configuration errors go undetected. It is very unlikely that returning a transient object outside the scope of an HTTP request is correct when the service is configured as with Per Web Request lifestyle. Developers expect (and depend) on the same instance being injected, which is not the case when returning a new instance each time. Instead of returning a transient object, the framework now (v1.6 and up) throws an exception when no HTTP context is available. Throwing an exception to make this explicit was the best thing to do since configuration errors would stay undetected for too long. If a transient object is in fact what is needed in that case; it can be easily configured.

There are two Stackoverflow questions that talk about this:

If you have any questions after reading these questions and their answers, please let me know.

Marked as answer by dot_NET_Junkie on 11/5/2013 at 7:33 AM