addScoped service lifetime in an ASP.NET Core multithreaded application

885 Views Asked by At

I know that AddSingleton() creates a single instance of the service when it is first requested and reuses that same instance in all the places where that service is needed.

If my ASP.NET Core application is multi-threaded, does that mean all HTTP requests from all users will share the same object instance created by dependency injection (DI)?

If so, that would be not a good way if the application process data to be stored. Are there any best practices?

2

There are 2 best solutions below

0
On BEST ANSWER

As mentioned in Microsoft documentation, Service lifetimes, it depends on your specific case.

Presumably, if you have a service, A, and you want to create a new instance on every single request, you can use AddScoped() rather than AddSingleton(). A scoped lifetime service would be created per client request.

0
On

If for example, it was some shared data that possibly doesn't change between requests such as some values that are computed at application startup and reused throughout the lifetime of the application, then that is a usable scenario.