simpleinjector / SimpleInjector

An easy, flexible, and fast Dependency Injection library that promotes best practice to steer developers towards the pit of success.
https://simpleinjector.org
MIT License
1.21k stars 154 forks source link

ThreadScopedLifestyle vs AsyncScopedLifestyle #991

Closed vkirienko closed 2 months ago

vkirienko commented 8 months ago

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.

dotnetjunkie commented 8 months ago

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);