Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Select Per-Thread or Per-Request Lifetime Scopes

Tags:

autofac

I am developing a library that is distributed internal to my company and consumed by a variety of applications. This library must be platform agnostic in that it may be deployed in a web context or even within a console app. I would like to register objects to be per-http-request or per-thread, depending on the context of the application consuming this framework. In StructureMap, I can do this using the Hybrid lifetime. Essentially, if an HttpContext exists then the object will be scoped to that, otherwise ThreadLocalStorage will be used on a per-thread basis. No additional configuration is required for the distributed library or the consuming application. Is this possible using Autofac? Given our wide variability of developer skill levels, our goal is to minimize/eliminate any specialized configuration for consumers.

I understand that registrations can be context agnostic using the InstancePerLifetimeScope lifetime, but then consuming applications are required to consume the ASP.NET/WCF/MVC integration binaries in order to bind InstancePerLifetimeScope registrations to an Http Request. Or, for per-thread scopes, the consuming code needs to have the responsibility of creating a lifetime scope per thread.

Any suggestions?

like image 386
Matt Scully Avatar asked Oct 04 '11 21:10

Matt Scully


1 Answers

It's easy to implement own lifetime manager that will check if 'HttpContext.Current != null' and then delegate to one of the existing managers.

I would however suggest that each application wire up appropriate manager itself. An example would be a unit test scenario where 'HttpContext' might not exist since it's mocked an you might want to control the lifetime manually for test specific purposes.

like image 151
Jakub Konecki Avatar answered Sep 22 '22 21:09

Jakub Konecki