Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleInjector RegisterWebApiRequest vs RegisterPerWebRequest

The latest version of SimpleInjector introduced a distinction between MVC and WebApi. Are the two request registrations aliases for the same thing? Or is there underlying differences as well?

Thanks

like image 995
tris Avatar asked Dec 19 '22 17:12

tris


1 Answers

The lifestyles and scope implementations WebRequest and WebApiRequest in SimpleInjector 2.5 are based on different technologies.

WebApiRequestLifestyle is derived from ExecutionContextScopeLifestyle which works well both inside and outside of IIS. I.e. it can function in a self-hosted WebAPI project where there is no HttpContext.Current. The scope used by WebApiRequestLifestyle is ExecutionContextScope. As the name implies an ExecutionContextScope registers itself in the logical call context and flows with async operations across threads (e.g. a continuation after await on a different thread still has access to the scope regardless of whether ConfigureAwait() was used with true or false).

In contrast, an instance of WebRequestLifestyle is stored within the HttpContext. The HttpContext can be used with WebAPI when it is hosted in IIS but care must be taken because it will not always flow with the execution context because the current HttpContext is stored in the IllogicalCallContext (see Understanding SynchronizationContext in ASP.NET). If you use await with ConfigureAwait(false) the continuation may lose track of the original HttpContext whenever the async-op does not execute synchronously. A direct effect of this is that it would no longer be possible to resolve the instance of a previously created service with WebRequestLifestyle from the container (e.g. in a factory that has access to the container) - and an exception would be thrown because HttpContext.Current would be null.

I would recommend you use WebApiRequestLifestyle for services that should be 'per Web API request', the most obvious example being services that are injected into WebAPI controllers. WebApiRequestLifestyle offers the following benefits:

  • the WebAPI controller can be used outside of IIS (e.g. in a self-hosted project)
  • the WebAPI controller can execute free-threaded (or multi-threaded) async methods because it is not limited to the ASP.net SynchronizationContext.

Check out the blog entry of Stephen Toub regarding the difference between ExecutionContext and SynchronizationContext.

like image 185
blueling Avatar answered Mar 15 '23 04:03

blueling