AddTransient, AddScoped and AddSingleton Services Differences

As you know that Dependency Injection is at the core of .Net Core. To register dependency injection in .Net Core application we use startup.cs file.

In this article, we will look into the 3 ways by which we can register Dependency Injection and we will see what are the difference among them.

AddTransient

The AddTransient method creates a new instance every time a service request is raised, doesn’t matter it is in the same HTTP request or a different HTTP request.

AdScoped

With AddScope() method, we get new instance with different HTTP requests. But we get the same instance if it is within the same scope.

AddSingleton

In AddSingleton() method, only one instance of service is created, when the service is executed for very first time. So, a single instance is created for a service, no matter how many times the service is being executed.

Read ASP.Net Core Interview Questions and Answers

Syntax to register Dependency Injection

Below are the code snippet, using this we can register the Dependency Injection within ConfigureService() method available in startup.cs file.

 public void ConfigureServices(IServiceCollection services)
        {
            
            //Transient 
            services.AddTransient<ITransientService, LifeCycleTest>();
            //Scoped
            services.AddScoped<IScopedService, LifeCycleTest>();
            //Singleton
            services.AddSingleton<ISingletonService, LifeCycleTest>();
        }

Watch AddTransient, AddScoped and AddSingleton Service demonstration in below video

Summary –

  • Transient objects are always different.
  • Scoped objects are same if the request generated from the same scope.
  • Singleton objects are always same and they use memory to serve the same objects, if you restart the service/ server then only Singleton object gets changed.
  • If you are not sure about which one to use to register Dependency Injection then use AddTransient method only.
  • Singleton objects are expensive as they uses memory, every time a request is generated.
You may read this - How to implement Dependency Injection in .NET 5?
Please follow and like us:

1 thought on “AddTransient, AddScoped and AddSingleton Services Differences”

Leave a Comment