What is the difference between a Transient and Scoped service?
What is the difference between a Singleton and a Transient service?
A Singleton service instance once created is reused for the entire application lifetime, whereas a Transient service instance is created every time a calling method or dependent class requests for it from the container.
What is a Scoped service?
A scoped service instance is created only once within a request scope and is reused for all calls within that request.
services.AddScoped<IMyClass, MyClass>();
What is a Transient service?
A transient service instance is created each time a calling component method or dependent class requests for an instance from the container.
services.AddTransient<IMyClass, MyClass>();
What is a Singleton service?
A singleton service instance is created only once during entire application lifetime, common across all requests.
services.AddSingleton<IMyClass, MyClass>();
What are service lifetimes in ASP.NET Core?
How do you register services?
A class can be registered as a service by adding it to the IServiceCollection instance under the ConfigureServices() method in the Startup class.
A class MyClass can be registered as a service in the below ways:
services.AddT<MyClass>(new MyClass()); (or)
services.AddT<new MyClass());
services.AddT<IMyClass, MyClass>(); (or)
services.AddT<IMyClass>(new MyClass());
Where T can be Singleton, Transient or Scoped.