Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีระบุอายุการใช้งานของบริการ (Service Lifetime) สำหรับบริการที่ลงทะเบียนเป็น Dependency ใน C# ASP.NET Core

คอนเทนเนอร์ IoC (Inversion of Control) มาตรฐานของ ASP.NET Core จัดการอายุการใช้งานของประเภทบริการที่ลงทะเบียนไว้ ระบบจะทำลายอินสแตนซ์ของบริการโดยอัตโนมัติตามอายุการใช้งานที่ระบุ

คอนเทนเนอร์ IoC รองรับอายุการใช้งาน 3 ประเภท

  • Singleton - คอนเทนเนอร์ IoC จะสร้างและแชร์อินสแตนซ์เดียวของบริการตลอดอายุการใช้งานของแอปพลิเคชัน
  • Transient - คอนเทนเนอร์ IoC จะสร้างอินสแตนซ์ใหม่ของประเภทบริการที่ระบุทุกครั้งที่มีการขอใช้งาน
  • Scoped - คอนเทนเนอร์ IoC จะสร้างอินสแตนซ์ของประเภทบริการที่ระบุหนึ่งครั้งต่อคำขอ (Request) และจะถูกแชร์ภายในคำขอเดียวกัน

ตัวอย่างการลงทะเบียนบริการด้วย ServiceDescriptor

public interface ILog { void Info(string str); }
class MyConsoleLogger : ILog {
    public void Info(string str) {
        Console.WriteLine(str);
    }
}

public class Startup {
    public void ConfigureServices(IServiceCollection services) {
        // Singleton - ส่งอินสแตนซ์โดยตรง
        services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger()));
        
        // Transient - ระบุประเภทและอายุการใช้งาน
        services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Transient));
        
        // Scoped - ระบุประเภทและอายุการใช้งาน
        services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Scoped));
    }
}

ตัวอย่างการลงทะเบียนบริการด้วย Extension Methods (แนะนำ)

public class Startup {
    public void ConfigureServices(IServiceCollection services) {
        // Singleton
        services.AddSingleton<ILog, MyConsoleLogger>();
        services.AddSingleton(typeof(ILog), typeof(MyConsoleLogger));
        
        // Transient
        services.AddTransient<ILog, MyConsoleLogger>();
        services.AddTransient(typeof(ILog), typeof(MyConsoleLogger));
        
        // Scoped
        services.AddScoped<ILog, MyConsoleLogger>();
        services.AddScoped(typeof(ILog), typeof(MyConsoleLogger));
    }
}

วิธีการใช้ Extension Methods เช่น AddSingleton, AddTransient, AddScoped เป็นวิธีที่แนะนำ เนื่องจากโค้ดอ่านง่ายกว่าและลดโอกาสเกิดข้อผิดพลาดได้