Service Lifetime is the duration for any services persist in Dependecy Injection Conatiner of any application. It is a way to representing the timeline of services that specify the time how long the Container will keep the instances of any requested services in DI conatiner after creation of these instances.
Dependency Injection Container :- is a place where we register the services and DI conatiner manages
these service instances and configure their Objects for an application based on the service type we used for registering the
Services in DI Container.
It is the responsibility of the DI Container to keep track on created services and disposal of these services when it is not required
or completed the lifetime.
Whenever application requested for any services DI Container is the only responsible to create the instances of the required
services at runtime based on their service type by which it is registered in DI Conatiner.
There are three types of services lifetime we used for registering the services are specified below.
Implementation of Services in MVC Core application :- I have explained the services implementation in details
using a Example in which you can easily understand the differences between AddTransient, AddScoped and Singleton services.
Below is the steps that i have used in my application for services implementation you can follow the same steps in your application also.
Below code is for displaying these three Interfaces created for each services.
public interface IScopedServiceType
{
Guid GetRequestID();
}
public interface ITransientServiceType
{
Guid GetRequestID();
}
public interface ISingletonServiceType
{
Guid GetRequestID();
}
Below is the code example for ServiceRequestClass that is implementing these three Interfaces.
public class ServiceRequestClass : ISingletonServiceType, IScopedServiceType, ITransientServiceType
{
Guid UniqueId;
public ServiceRequestClass()
{
UniqueId = Guid.NewGuid();
}
public Guid GetRequestID()
{
return UniqueId;
}
}
After creating the Interfaces and Service class you need to register these services into the DI Container in Program.cs file as shown in below Image and Program.cs file code.
using BloggingExamples.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DBCS")));
builder.Services.AddScoped (ScopedServiceType, ServiceRequestClass)();
builder.Services.AddTransient(ITransientServiceType, ServiceRequestClass)();
builder.Services.AddSingleton(ISingletonServiceType, ServiceRequestClass)();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=AspCoreService}/{action=CheckServiceType}/{id?}");
app.Run();
After registering the Services into Program.cs file now we need to use them in controller using the constructor dependency injection as shown in below Image and code snippet.
public class AspCoreServiceController : Controller
{
private readonly IScopedServiceType _servicesScoped;
private readonly ITransientServiceType _servicesTransient;
private readonly ISingletonServiceType _servicesSingleton;
private readonly IScopedServiceType _servicesScoped2;
private readonly ITransientServiceType _servicesTransient2;
private readonly ISingletonServiceType _servicesSingleton2;
public AspCoreServiceController(IScopedServiceType scopedServiceType,ITransientServiceType transientServiceType,
ISingletonServiceType singletonServiceType, IScopedServiceType scopedServiceType2, ITransientServiceType transientServiceType2,
ISingletonServiceType singletonServiceType2)
{
_servicesScoped = scopedServiceType;
_servicesTransient = transientServiceType;
_servicesSingleton = singletonServiceType;
_servicesScoped2 = scopedServiceType2;
_servicesTransient2 = transientServiceType2;
_servicesSingleton2 = singletonServiceType2;
}
public IActionResult CheckServiceType()
{
ViewBag.ScopeTypeFirstRequest = _servicesScoped.GetRequestID();
ViewBag.ScopeTypeSecondRequest = _servicesScoped2.GetRequestID();
ViewBag.TransientTypeFirstRequest = _servicesTransient.GetRequestID();
ViewBag.TransientTypeSecondRequest = _servicesTransient2.GetRequestID();
ViewBag.SingletonTypeFirstRequest = _servicesSingleton.GetRequestID();
ViewBag.SingletonTypeSecondRequest = _servicesSingleton2.GetRequestID();
return View();
}
}
Create a View and use the Viewbag stored GUID from different requests as you can see into the below image that is for a cshtml view of the Action method.
Now run the application in two tabs we are considering it as a Request Number 1 and you can see into the table for different
service types has different request Id for Request in single browser.
First Request
Now run the application in two different browsers and we are considering it as a Request Number 2 and you can see into the table for different
service types has different request Id for Request in both the browsers.
Second Request
Conclusion :- As you can see into above images we conclude that Transient services created different instances for each and every request and Scoped Services created a single instance for a specific HTTP request and share that to throughout but for other request it is different from first one. Singleton services are created only single instance for a request and used globally all over the application.
About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the
applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server,
EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.