Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct 'per request' Simple Injector lifestyle to use in a ServiceStack API application?

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':

  1. Per Web Request
  2. Per Web API 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?

like image 412
David Avatar asked Mar 05 '14 11:03

David


1 Answers

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.

like image 132
Steven Avatar answered Nov 02 '22 03:11

Steven