Top Misconceptions About Dependency Injection in ASP.NET Core

Which can even lead to bugs.

Sasha Marfut
Level Up Coding
Published in
5 min readOct 2, 2021

--

Photo by Nubelson Fernandes on Unsplash

In my job, I regularly notice that developers who have recently started working with dependency injection in ASP.NET Core, or those who do not pay enough attention to this topic, have a list of misconceptions.

Some misconceptions cause bugs, while others lead to redundant coding. Let’s take a look at the ones I’ve found to be the most repetitive.

Scoped Class Created Only Once per Web Request

Developers can choose one out of three lifetimes when registering a class using dependency injection in ASP.NET Core: transient, scoped, and singleton.

Transient means that a new instance of the class is created every time it is requested from the DI container. Singleton means that a single instance of the class will be created for the entire application lifetime. It will be shared across web requests and disposed only on the application shut down.

When the instance of the class should be created once per web request, developers use scoped lifetime:

public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IUserRepository, UserRepository>();
}

However, scoped lifetime does not guarantee that a scoped class is only created once for each web request. A scoped lifetime means the class will only be instantiated once in a given scope, but multiple scopes can be created in a single web request.

In simple words, in ASP.NET Core, scope is the area of code between instantiating an IServiceScope type and calling its Dispose method.

IServiceScope instance contains the ServiceProvider property that is used to resolve instances that were registered in ConfigureServices method.

If the same type within a scope is resolved multiple times, there will be always the same instance returned.

--

--