ASP.NET Core AddSingleton vs AddScoped vs AddTransient

In .net core while register services with dependency injection container in “ConfigureServices(IServiceCollection services)” in Startup.cs, we can define the lifetime of the instance across the application using any one of the three methods.

AddSingleton

  • Only one instance will create and that instance will be available through out the application.
  • So that when ever we need the instance that created during application start we could able to access it at any point in the application.
  • At any number of http request we could able to access the same instance

AddScoped

  • For each http request new instance will gets created.
  • The instance gets created using AddScoped, will be alive only for that particular http request

AddTransient

  • Irrespective of http request, every time when we look for an instance, it will create an instance every time
  • Example, in an single http request if we are trying to access Student repository instance more than a time, each time it will create new instance separately

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: