AddTransient, AddScoped and AddSingleton Services Differences

As you know that Dependency Injection is in 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

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

AdScoped

With AddScope() method, we get new instance with different http requests. But we get 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 at 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 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:

Leave a Comment