Search code examples
asp.netdependency-injectionaspnetcore-environment

addScoped service lifetime in an ASP.NET Core multithreaded application


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?


Solution

  • 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.