Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 인터페이스 기반 주입(Interface Injection)으로 의존성 주입 구현하는 방법

의존성 주입(Dependency Injection)이란?

결합되어 있는(종속적인) 객체를 분리된(독립적인) 객체로 전환하여 주입하는 과정을 의존성 주입(Dependency Injection, DI)이라고 합니다. DI를 적용하면 객체 간 결합도가 낮아져 코드의 유연성, 재사용성, 테스트 용이성이 크게 향상됩니다.

의존성 주입의 네 가지 유형

  • 생성자 주입(Constructor Injection)

  • 세터 주입(Setter Injection)

  • 인터페이스 기반 주입(Interface-based Injection)

  • 서비스 로케이터 주입(Service Locator Injection)

인터페이스 주입(Interface Injection)이란?

인터페이스 주입은 게터(Getter)와 세터(Setter)를 이용하는 DI 방식과 유사합니다. 다만 일반적인 Getter/Setter DI는 기본 프로퍼티 접근자를 사용하는 반면, 인터페이스 주입은 별도의 지원(support) 인터페이스를 통해 인터페이스 타입의 속성을 명시적으로 설정한다는 점이 다릅니다. 즉, 의존성을 주입받는 클래스가 반드시 특정 인터페이스를 구현하도록 강제함으로써 주입 계약(injection contract)을 명확하게 만들어 줍니다.

예제 코드

public interface IService{
    string ServiceMethod();
}
public class ClaimService : IService{
    public string ServiceMethod(){
        return "ClaimService is running";
    }
}
public class AdjudicationService : IService{
    public string ServiceMethod(){
        return "AdjudicationService is running";
    }
}
interface ISetService{
    void setServiceRunService(IService client);
}
public class BusinessLogicImplementationInterfaceDI : ISetService{
    IService _client1;
    public void setServiceRunService(IService client){
        _client1 = client;
        Console.WriteLine("Interface Injection ==> 
        Current Service : {0}", _client1.ServiceMethod());
    }
}

위 코드의 구조를 살펴보면 다음과 같습니다.
- IService: 서비스 계약을 정의하는 인터페이스입니다.
- ClaimService, AdjudicationService: IService를 구현하는 구체적인 서비스 클래스입니다.
- ISetService: 의존성을 주입하기 위한 메서드 시그니처를 규정하는 인터페이스입니다.
- BusinessLogicImplementationInterfaceDI: ISetService를 구현하여 외부에서 전달받은 서비스 객체를 내부 필드에 저장하고 사용하는 비즈니스 로직 클래스입니다.

구현체 사용하기

BusinessLogicImplementationInterfaceDI objInterfaceDI =
new BusinessLogicImplementationInterfaceDI();
serviceObj = new ClaimService();
objInterfaceDI.setServiceRunService(serviceObj);

클라이언트 코드는 구체적인 구현 클래스에 직접 의존하지 않고 IService 인터페이스를 통해서만 서비스를 참조합니다. 따라서 필요에 따라 ClaimService 대신 AdjudicationService 등 다른 구현체로 손쉽게 교체할 수 있으며, 이것이 인터페이스 기반 의존성 주입의 핵심 장점입니다.