종속성 주입(Dependency Injection, DI)은 객체 간의 결합도를 낮추고 테스트와 유지보수를 쉽게 하는 디자인 패턴입니다. C#에서는 DI를 효율적으로 사용하기 위해 IServiceProvider 인터페이스를 활용할 수 있습니다.
1. DI 패턴 이해하기
DI는 객체가 직접 다른 객체를 생성하지 않고, 필요한 의존성을 외부에서 주입받는 방식입니다. 이렇게 하면 확장성과 테스트 용이성이 크게 향상됩니다.
2. IServiceProvider 기본 사용법
IServiceProvider는 등록된 서비스를 요청할 때 사용합니다. 보통은 Microsoft.Extensions.DependencyInjection 네임스페이스를 통해 DI 컨테이너를 구성합니다.
3. 간단한 DI 예제
using System;
using Microsoft.Extensions.DependencyInjection;
public interface IMessageService
{
void Send(string message);
}
public class EmailService : IMessageService
{
public void Send(string message)
{
Console.WriteLine($"Email Service: {message}");
}
}
class Program
{
static void Main(string[] args)
{
// 서비스 컬렉션 생성
var services = new ServiceCollection();
// 서비스 등록
services.AddTransient();
// 서비스 프로바이더 빌드
IServiceProvider provider = services.BuildServiceProvider();
// 서비스 요청
var messageService = provider.GetService();
messageService?.Send("Hello Dependency Injection!");
}
}
4. 요약
C#의 DI 패턴을 통해 유연한 코드 작성이 가능하며, IServiceProvider는 등록한 서비스를 요청하는 표준 인터페이스입니다. 이를 적절히 활용하면 가독성 좋고 확장성 있는 애플리케이션을 만들 수 있습니다.
'C#' 카테고리의 다른 글
| C# IDisposable을 통한 비관리 리소스 해제 사례 (1) | 2026.06.01 |
|---|---|
| C# 암호화 해시(Checksum) 생성과 비교 (0) | 2026.06.01 |
| C# System.FormattableString으로 다국어 문자열 처리 (0) | 2026.05.30 |
| C# AttributeTargets로 애트리뷰트 적용 범위 제어 (0) | 2026.05.29 |
| C# BinarySearch와 검색 알고리즘 성능 비교 (0) | 2026.05.29 |