Dependency Container and Service Lifetimes
In .NET we have a powerful tool that helps us follow SOLID’s D (Dependency inversion). And that is Dependency Injection (DI) in .NET. Using DI, we can avoid creating a new instance for classes that we use in our software every time we want. We can just register them in our Dependency Container and assign them lifetimes. How we manage doing this, we will talk about it in this article, let’s go!
Dependency container
Using Microsoft.Extensions.Hosting package we can achieve creating containers for our services.
Use dotnet add package Microsoft.Extensions.Hosting command in terminal.
For creating container and adding it our services, follow this syntax:
var builder = new HostApplicationBuilder();
Here it is. Now we have our container created. Now can register our services to it. Let’s see it!
Service lifetimes
Now we will register our services so that we will not have to create a new instance every time we are using that class in our software. We will give interface of that class and the implementation itself.
There are three types of Service lifetimes:
Use transient when you need something that should be changed every time when you use it. For example for unique IDs (let’s say GUID service). We can register our service as Transient like this:
领英推荐
builder.Services.AddTransient<IService, Service>();
Use scoped when you want to share data in one scope in let’s say one HTTP Request. We can have multiple scopes in our software. Every scope will have their own instances, not effecting each other.
builder.Services.AddScoped<ITimeProvider, TransientTimeProvider>();
You may create multiple scopes after building application. Use this:
var scopeProvider = application.Services.GetRequiredService<IServiceScopeFactory>();
Scopes are IDisposable and every time when the work is done, every instances are deleted.
Use Singleton when you want your service to serve across the software from when it is started till it’s end. What I mean is when you register your service as singleton and when it is called multiple times, every time the first created one will be shared across the entire software. For example count service.
services.AddSingleton<IMyService, MyService>();
Hosted services
Hosted services work even we do not call them. We just have to register them in dependency container as Hosted Service like this:
builder.Services.AddHostedService<HostedService>();
For example you need a service that updates software’s state in every ten seconds:
public class BackgroundTaskService : IHostedService
{
private Timer timer;
public Task StartAsync(CancellationToken cancellationToken)
{
timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));
return Task.CompletedTask;
}
private void DoWork(object state)
{
Console.WriteLine("Program is working");
}
public Task StopAsync(CancellationToken cancellationToken)
{
timer?.Dispose();
return Task.CompletedTask;
}
}
This will automatically prints in every 10 seconds.
.NET Developer | Software Engineer | Open Source Contributor | Skilled in Problem-Solving and Error Analysis | Passionate About Crafting Scalable Solutions
4 个月????
Mentor
4 个月Assalomu Alaykum Muhammad maqola yaxshi yozilgan faqat o’zbek tilida kontentlarni dasturlash bo’yicha ko’paytirsak zo’r bo’lar edi shu fikrimga nima deysiz?