Setter Injection (Property Injection) คือการส่ง Dependency ผ่าน Property แบบ Public (get/set) แทนที่จะส่งผ่าน Constructor
ตัวอย่างโค้ด
// Service Interface
public interface IService
{
string ServiceMethod();
}
public class ClaimService : IService
{
public string ServiceMethod() => "ClaimService is running";
}
public class AdjudicationService : IService
{
public string ServiceMethod() => "AdjudicationService is running";
}
// Consumer ใช้ Property สำหรับรับ Dependency
public class BusinessLogic
{
private IService _service;
public IService Service
{
get => _service;
set => _service = value;
}
public void Execute()
{
if (_service == null)
throw new InvalidOperationException("Service not injected");
Console.WriteLine($"Setter Injection => Current Service: {_service.ServiceMethod()}");
}
}
การใช้งาน
var logic = new BusinessLogic();
logic.Service = new ClaimService(); // Set ผ่าน Property
logic.Execute();
เมื่อไหร่ควรใช้ Setter Injection?
- Dependency เป็น Optional (ไม่จำเป็นต้องมีตอนสร้างออบเจกต์)
- ต้องการเปลี่ยน Dependency หลังสร้างออบเจกต์แล้ว (Runtime swapping)
- มี Dependency หลายตัวที่ Optional พร้อมกัน (Constructor Injection จะทำให้ Constructor ยาวเกินไป)
ข้อควรระวัง
- อาจเกิด NullReferenceException หากลืม Set Property ก่อนใช้งาน
- DI Container บางตัว (เช่น ASP.NET Core Built-in) ไม่รองรับ Property Injection โดยตรง ต้องใช้ Library เสริมเช่น Autofac
- ลดความชัดเจนของ Dependency (ไม่เห็นได้จาก Constructor)
แนวทางปัจจุบัน
แนะนำให้ใช้ Constructor Injection เป็นหลัก สำหรับ Mandatory Dependencies ใช้ Setter Injection เฉพาะ Optional Dependencies เท่านั้น