I have a ServiceStack API application which uses Simple Injector as its IoC container. I need certain components to have a 'per web request' lifestyle.
I looked up in the Simple Injector documentation here, and found that it has not one, but two lifestyles corresponding to 'per web request':
This confused the hell out of me because I always thought all ASP.NET applications used the same basic pipeline, and that IoC containers implemented per web request by plugging in an HTTP module. Why would this be different for Web API applications?
Can anyone shed some light about which is most appropriate for a ServiceStack API application?
The Per Web Request is actually a 'Per HttpContext Request', and under the cover it caches instances using the HttpContext.Current.Items
dictionary. This model however starts to break down quickly when you're using Web API, which is caused by the asynchronous model of Web API and the fact that Web API applications can run in a self-hosted environment (which means: no there's no HttpContext.Current
at all).
That's why Simple Injector provides a specific lifestyle for Web API applications. This Per Web API Request lifestyle uses the new Execution Context Scope in the background which allows flowing the scope with asynchronous methods.
Can anyone shed some light about which is most appropriate for a ServiceStack API application?
If ServiceStack is asynchronous in nature or is self-hosted, you're better of with the WebApiRequestLifestyle
or the ExecutionContextScopeLifestyle
. If there's always a HttpRequest.Current when running inside ServiceStack you can use the WebRequestLifestyle
.
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