DEV Community

Feruzbek Raximboyev
Feruzbek Raximboyev

Posted on

Dependency Injection Container and Service Lifetimes

• Dependency Injection Container nima?

Dependency Injection Container - qisqacha DI Container Dependency Injectionni amalga oshiruvchi mexanizm bo'lib, uning vazifasi dasturdagi servicelarni ro'yxatga olish, servicelarga kerakli bo'lgan boshqa service obyektlarini servicening konstruktoriga tashqaridan Inject qilib berishdir.

• Dependency Injection nima?

Dependency Injection — tashqi manbaga muhtoj har bir class o'ziga kerakli boshqa class obyektlarini shu classning o'zida yaratish o'rniga DI konteynerdan olish orqali kamroq bog‘lanish va yaxshiroq test qilinishni ta'minlaydigan dizayn patterndir. DI dan foydalanish kodni ancha moslashuvchanva osonlikcha kengayuvchanholatga olib keladi.

• Eslatma!

Host yaratish va Dependency Injectiondan foydalanish uchun Microsoftning High level darajadagi kutubxonalari.

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection

• .NET da Host Application yaratish.

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;

var builder = new HostApplicationBuilder();

//ushbu qatorda DI Containerga servicelar qo'shiladi

var application = builder.Build(); //Host yaratish

application.Run(); //Dasturni ishga tushirish

• Service Lifetimes

Service Lifetimes - DI Containerga ro'yxatga olingan servicening namunasi dastur ishlashi davomida qancha vaqt yashashi va qancha nusxada yaratilishiga qarab servicelar Service Lifetimelarga bo'linadi. DI Containerga servicelar asosan Transient, Singleton va Scoped kabi Lifetimelarda qo'shiladi.

1. Transient Services - bunday turdagi servicelarning namunalari har safar chaqirilganda yangi yaratiladi. Ya'ni DI Container har safar servicening yangi obyektini yaratadi.

//Serviceni DI Containerga Transient qilib qo'shish
AddTransient<TService, TImplementation>(); 
Enter fullscreen mode Exit fullscreen mode
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;

var builder = new HostApplicationBuilder();

// Servicelarni DI Containerga qo'shish.
builder.Services.AddTransient<ITransientService, TransientService>();

var application = builder.Build();

// Servicelarni DI Containerdan olish.
var transientService1 = application.Services.GetRequiredService<ITransientService>();
var transientService2 = application.Services.GetRequiredService<ITransientService>();
var transientService3 = application.Services.GetRequiredService<ITransientService>();

transientService1.Print();
transientService2.Print();
transientService3.Print();

application.Run();

public class TransientService : ITransientService
{
    private int id = 1;
      private string currentTime = DateTime.Now.ToString("HH:mm:ss:ff");

   public void Print() 
    => Console.WriteLine($"{id++}, vaqt: {currentTime}");
}
public interface ITransientService 
{
    public void Print();
}
Enter fullscreen mode Exit fullscreen mode
//Har bir servcice uchun DI Containerda yangi obyekt yaratilyapti!
Output
1, vaqt: 22:49:13:10
1, vaqt: 22:49:13:11
1, vaqt: 22:49:13:12
Enter fullscreen mode Exit fullscreen mode

2. Singleton Services - ushbu turdagi servicelarning faqat bitta nusxasi bo'ladi va har safar ushbu service namunasiga murojaat qilinganda shu nusxaga murojaat qilinadi. Ya'ni dastur ishlashi davomida faqat bitta obyekt ustida ish bajariladi.

//Serviceni DI Containerga Singleton qilib qo'shish
AddSingleton<TService, TImplementation>(); 
Enter fullscreen mode Exit fullscreen mode
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;

var builder = new HostApplicationBuilder();

//Servicelarni DI Containerga qo'shish.
builder.Services.AddSingleton<ISingletonService, SingletonService>();

var application = builder.Build();

//Servicelarni DI Containerdan olish.
var singletonService1 = application.Services.GetRequiredService<ISingletonService>();
var singletonService2 = application.Services.GetRequiredService<ISingletonService>();

singletonService1 .Print();
singletonService2 .Print();

application.Run();
public class SingletonService : ISingletonService
{
    private int id = 1;
    private string currentTime = DateTime.Now.ToString("HH:mm:ss:ff");


    public void Print() 
      => Console.WriteLine($"{id++}, vaqt: {currentTime}");
}

public interface ISingletonService 
{
    public void Print();
}
Enter fullscreen mode Exit fullscreen mode
//DI Containerda hamma servicelar uchun bitta instance yaratilyapti
Output
1, vaqt: 22:59:21:97
2, vaqt: 22:59:21:97
Enter fullscreen mode Exit fullscreen mode

3. Scoped Services - IServiceScopeProvider orqali yaratilgan scope ichida servicening istalgancha namunalarini yaratsak ham barchasi bitta obyetkga murojaat qilishadi.

//Serviceni DI Containerga scoped qilib qo'shish
AddScoped<TService, TImplementation>(); 
Enter fullscreen mode Exit fullscreen mode
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;

var builder = new HostApplicationBuilder();

// Servicelarni DI Containerga qo'shish.
builder.Services.AddScoped<IScopedService, ScopedService>();

var application = builder.Build();

//IServiceScopeFactory dan foydalanib scope yaratish.
 var scopeProvider = application.Services.GetRequiredService<IServiceScopeFactory>();

 using(var scope = scopeProvider.CreateScope())
{
    var scopedService1 = scope.ServiceProvider.GetRequiredService<IScopedService>();
    var scopedService2 = scope.ServiceProvider.GetRequiredService<IScopedService>();

    scopedService1.Print();
    scopedService2.Print();
}

application.Run();

public class ScopedService : IScopedService
{
    private int id = 1;
    private string currentTime = DateTime.Now.ToString("HH:mm:ss:fff");

   public void Print() 
    => Console.WriteLine($"{id++}, vaqt: {currentTime}");
}

public interface IScopedService 
{
    public void Print();
}
Enter fullscreen mode Exit fullscreen mode
//Scope ichidagi barcha servicelar bitta instancega murojaat qilyapti.
Output
1, vaqt: 00:58:46:926
2, vaqt: 00:58:46:926
Enter fullscreen mode Exit fullscreen mode

Top comments (0)