When working in the ConfigureServices in the startup class, we deal with Dependency Inject (DI). More precisely we create what is called a DI Container within ConfigureServices. We have to determine what is the appropriate method (AddTransient, AddScoped, and AddSingleton) to use to inject these services into the DI. This post will look at when to use AddTransient, AddScoped, and AddSingleton.

  • AddTransient - When a service is injected using AddTransient, a new instance is created every time a request is made whether that is part of an HTTP request that is the same or HTTP requests that are different.

  • AddScoped - When a service is injected using AddScoped, scope-wise, the same instance is used in the HTTP request, while a new instance is created when using it across HTTP requests that are different.

  • AddSingleton - When a service is injected using AddSingleton, scope-wise, the same instance is used in the HTTP request and the same instance is used across HTTP requests that are different.