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

การทำ Dependency Injection แบบ Interface-based Injection ใน C#

Dependency Injection (DI) คือการแปลงออบเจกต์ที่มีการผูกมัดกัน (Coupled) ให้กลายเป็นอิสระต่อกัน (Decoupled) โดยการส่งออบเจกต์ที่ต้องการ (Dependency) เข้าไปจากภายนอก แทนที่จะสร้างเองภายในคลาส

ประเภทของ Dependency Injection

  1. Constructor Injection
  2. Setter Injection (Property Injection)
  3. Interface-based Injection
  4. Service Locator Injection

Interface-based Injection

คล้ายกับ Setter Injection แต่แทนที่จะใช้ Property ธรรมดา จะใช้ Interface เป็นตัวกลางในการตั้งค่า Dependency โดย Interface นี้จะมีเมธอดสำหรับรับ Dependency (Explicit Setter)

ตัวอย่างโค้ด

// 1. Interface ของ Service
public interface IService
{
    string ServiceMethod();
}

// 2. Implementation ต่างๆ
public class ClaimService : IService
{
    public string ServiceMethod() => "ClaimService is running";
}

public class AdjudicationService : IService
{
    public string ServiceMethod() => "AdjudicationService is running";
}

// 3. Interface สำหรับ Injection (Setter แบบ Explicit)
public interface ISetService
{
    void SetService(IService service);
}

// 4. Consumer ที่ implement ISetService
public class BusinessLogic : ISetService
{
    private IService _service;

    public void SetService(IService service)
    {
        _service = service;
        Console.WriteLine($"Interface Injection => Current Service: {_service.ServiceMethod()}");
    }
}

การใช้งาน (Consuming)

var logic = new BusinessLogic();
logic.SetService(new ClaimService());     // ใช้ ClaimService
logic.SetService(new AdjudicationService()); // เปลี่ยนเป็น AdjudicationService

ข้อดีและข้อเสีย

  • ข้อดี: ชัดเจนว่า Class นี้ต้องการ Dependency อะไร (ผ่าน Interface), รองรับการเปลี่ยน Dependency ระหว่างรันไทม์
  • ข้อเสีย: เพิ่มความซับซ้อน ต้องสร้าง Interface เพิ่ม, ไม่ค่อยใช้ในปัจจุบัน (Constructor Injection เป็นที่นิยมกว่า)

แนวทางปัจจุบัน

ใน ASP.NET Core และ Modern C# มักใช้ Constructor Injection ร่วมกับ DI Container (IServiceCollection) ซึ่งจัดการ Lifetime (Singleton, Scoped, Transient) ให้อัตโนมัติ