Dotnet Core service injection configuration

As you may already know, asp.net core comes with a built-in dependency injection system which is very easy to configure with simple instruction. The only pain point for me, is that I can’t remember what are the difference between the different way to configure the injection… So if like me you sometimes have a goldfish memory, here is a quick refresh.

If you want to learn more, take a look at the official documentation : https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2

“architectural photography of building” by Dan Gold on Unsplash

Where are we ?

This small article focus on the Startup.cs file of a asp.net core project. In that file, there is a method where you can configure the services injection :

public void ConfigureServices(IServiceCollection services)
{
// here you can register your services to inject e.g
services.AddTransient<IHelloService, HelloService>();
}

As you can see, you can add to the service collection list, a link that inform asp.net core that it has to inject a specific class (second generic type = HelloService) everytime it find the following interface (first generic type = IHelloService).

AddSingleton

services.AddSingleton<IApplicationService, ApplicationService>();
One instance of the service for the entire application.

In that case, only one instance of the service will be created and reused throughout the application life. All saved values can then be reused at any time.

AddTransient

services.AddTransient<IEphemeralService, EphemeralService>();
Anytime the service is needed, create a new instance.

There is no need to save something for the next uses, we just recreate a fresh new instance at every use.

AddScoped

services.AddScoped<IRequestService, RequestService>();
One instance per HTTP request.

The service is scoped to a specific request where it’s reused anytime the code needs it. Once the HTTP request as returned the response to the client, the service is thrown away.