SimpleInjector
SimpleInjector copied to clipboard
ThreadScopedLifestyle vs AsyncScopedLifestyle
HI,
I'm trying to understand what is real life difference between ThreadScopedLifestyle and AsyncScopedLifestyle in .NET Core application.
We have services that are used during HTTP request processing as well as in background jobs on explicitly created threads with ThreadScopedLifestyle scope. For that we created HybridLifestyle that uses one or another based on presence of HttpContext, that supports MVC, WebApi and background jobs.
Now comes migration to .NET Core and I wonder if really need HybridLifestyle like below at all or simple AsyncScopedLifestyle would be good to cover all three cases.
private static readonly ScopedLifestyle HybridLifestyle =
Lifestyle.CreateHybrid(
defaultLifestyle: new AsyncScopedLifestyle(),
fallbackLifestyle: new ThreadScopedLifestyle()
);
Thank you.
The ThreadScopedLifestyle is a legacy lifestyle, which is included solely for backwards compatibility. For modern applications, you should primarily use the AsyncScopedLifestyle as this lifestyle works in both async and single-threaded scenarios.
When solely depending on the AsyncScopedLifestyle as scoped lifestyle, there is also no need to use the hybrid lifestyle.
This simplifies your registration as you can simply do the following:
var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.Register<IUnitOfWork, SqlUnitOfWork>(Lifestyle.Scoped);