Dependency Container and Service Lifetimes

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:

  • Transient
  • Scoped
  • Singleton

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.

Ibrohim Qosimov

.NET Developer | Software Engineer | Open Source Contributor | Skilled in Problem-Solving and Error Analysis | Passionate About Crafting Scalable Solutions

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?

要查看或添加评论,请登录

Muhammad Khodjaev的更多文章

  • React+Typescript’da SSO

    React+Typescript’da SSO

    Maqolani boshlashdan oldin SSO haqida bir shingil: Single-Sign-On — bir martta аутентификация dan o’tgandan so’ng…

  • Get Service method’larni to’g’ri design qilish

    Get Service method’larni to’g’ri design qilish

    Servislarda method’lar yozayotganda ularni to’g’ri implementatsiya qilish juda muhim. Tasavvur qiling, bitta…

  • Git. Nom beramiz.

    Git. Nom beramiz.

    Qachonki Git yordamida jamoaviy yoki o’zimiz ishlayotganimizda, Git’dagi barcha narsani to’g’ri nomlash o’ta muhim va…

    1 条评论
  • .NET’da Exception (istisno)…

    .NET’da Exception (istisno)…

    Dastur ishlab chiqish jarayonida, istisno holatlar (maqola davomida Exception (eksepshin) deyiladi) xatoliklar (error)…

  • .NET’da Validatsiya

    .NET’da Validatsiya

    Maqolani boshlashdan avval validatsiya o’zi nima ekanligi haqida bir og’iz: Validatsiya — bu, ma'lumotlarni saqlash…

  • .NET’da Logging | ILogger<>

    .NET’da Logging | ILogger<>

    .NET’da log qilish (qayd qilish) oson ishlardan biri albatta.

    1 条评论

社区洞察

其他会员也浏览了