팩터리와 옵션 패턴
팩터리 대리자, IServiceProvider, Options 패턴을 사용해 조건부 또는 구성 가능한 의존성을 처리합니다.
팩터리와 옵션 패턴은(는) CoddyKit의 무료 C# Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C# Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C# Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
생성자 주입만으로는 부족한 경우
런타임 데이터에 따라 조건부로 서비스를 생성하거나 사용 사례마다 다르게 구성해야 할 때가 있습니다. 이럴 때 팩토리 패턴과 옵션 패턴이 유용합니다.
AddTransient를 사용한 팩토리 대리자
AddTransient, AddScoped 또는 AddSingleton에 팩토리 대리자를 전달할 수 있습니다. 대리자는 IServiceProvider를 받아 다른 서비스를 해결할 수 있습니다.
builder.Services.AddTransient<IPaymentGateway>(sp =>
{
var config = sp.GetRequiredService<IOptions<PaymentConfig>>().Value;
return config.Provider == "stripe"
? new StripeGateway(config.ApiKey)
: new PayPalGateway(config.ClientId, config.Secret);
});IOptionsSnapshot을 사용한 이름 있는 옵션
옵션 패턴은 구성 섹션을 강한 형식의 클래스에 바인딩합니다. 싱글턴에는 IOptions<T>를 사용하고, 요청마다 갱신되는 값에는 IOptionsSnapshot<T>를 사용하십시오.
public class SmtpSettings
{
public string Host { get; set; } = "";
public int Port { get; set; } = 587;
public string Username { get; set; } = "";
}
// Registration
builder.Services.Configure<SmtpSettings>(
builder.Configuration.GetSection("Smtp"));
// Consumption
public class EmailService
{
private readonly SmtpSettings _settings;
public EmailService(IOptions<SmtpSettings> opts)
=> _settings = opts.Value;
}핫 리로드를 위한 IOptionsMonitor
IOptionsMonitor<T>는 액세스하는 시점의 현재 옵션 값을 제공하고 구성 변경을 알려 줍니다. 따라서 실시간 구성 업데이트가 필요한 싱글턴에 적합합니다.
public class FeatureFlagService
{
private readonly IOptionsMonitor<FeatureFlags> _monitor;
public FeatureFlagService(IOptionsMonitor<FeatureFlags> monitor)
=> _monitor = monitor;
public bool IsEnabled(string flag)
{
// Always reads the latest config value
return _monitor.CurrentValue.Flags.GetValueOrDefault(flag);
}
}이름 있는 옵션
이름 있는 옵션을 사용하면 동일한 형식의 구성을 여러 개 등록할 수 있습니다. Configure<T>(name, ...)을 사용하여 등록하고 IOptionsSnapshot<T>.Get(name)으로 해결하십시오.
builder.Services.Configure<S3Settings>("primary",
builder.Configuration.GetSection("S3:Primary"));
builder.Services.Configure<S3Settings>("backup",
builder.Configuration.GetSection("S3:Backup"));
public class S3Service
{
public S3Service(IOptionsSnapshot<S3Settings> opts)
{
var primary = opts.Get("primary");
var backup = opts.Get("backup");
}
}시작 시 옵션 유효성 검사
ValidateDataAnnotations() 또는 사용자 지정 유효성 검사기를 사용하여 애플리케이션이 시작되기 전에 구성이 올바른지 확인하십시오. ValidateOnStart()와 함께 사용하면 즉시 실패하도록 만들 수 있습니다.
public class SmtpSettings
{
[Required] public string Host { get; set; } = "";
[Range(1, 65535)] public int Port { get; set; } = 587;
}
builder.Services
.AddOptions<SmtpSettings>()
.Bind(builder.Configuration.GetSection("Smtp"))
.ValidateDataAnnotations()
.ValidateOnStart();추상 팩토리 패턴
추상 팩토리 인터페이스를 사용하면 서비스에 팩토리를 주입하고 런타임 데이터를 사용할 수 있을 때까지 생성을 지연할 수 있습니다. 이때 IServiceProvider에 직접 의존하지 않아도 됩니다.
public interface IReportFactory
{
IReport Create(string reportType);
}
public class ReportFactory : IReportFactory
{
private readonly IServiceProvider _sp;
public ReportFactory(IServiceProvider sp) => _sp = sp;
public IReport Create(string reportType) => reportType switch
{
"pdf" => _sp.GetRequiredService<PdfReport>(),
"excel"=> _sp.GetRequiredService<ExcelReport>(),
_ => throw new ArgumentException("Unknown type")
};
}
builder.Services.AddTransient<IReportFactory, ReportFactory>();키 기반 서비스(.NET 8)
.NET 8에서는 키 기반 서비스가 도입되었습니다. 서로 다른 키로 여러 구현을 등록하고 [FromKeyedServices] 또는 GetKeyedService를 사용하여 적절한 구현을 해결할 수 있습니다.
builder.Services.AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe");
builder.Services.AddKeyedScoped<IPaymentGateway, PayPalGateway>("paypal");
// Resolve in a class:
public class CheckoutService(
[FromKeyedServices("stripe")] IPaymentGateway stripe,
[FromKeyedServices("paypal")] IPaymentGateway paypal) { }재정의를 위한 PostConfigure
PostConfigure는 모든 Configure 호출이 끝난 후 실행됩니다. 테스트에서 재정의를 적용하거나 어떤 구성이 로드되었는지와 관계없이 불변 조건을 적용할 때 사용하십시오.
// In integration tests: force test values after real config
builder.Services.PostConfigure<SmtpSettings>(opts =>
{
opts.Host = "smtp.test.local";
opts.Port = 25;
});IServiceCollection 확장 메서드
등록을 확장 메서드로 묶어 Program.cs를 깔끔하게 유지하고 여러 프로젝트에서 모듈을 재사용할 수 있도록 하십시오.
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddPaymentServices(
this IServiceCollection services,
IConfiguration config)
{
services.Configure<PaymentConfig>(config.GetSection("Payment"));
services.AddScoped<IPaymentGateway, StripeGateway>();
services.AddScoped<PaymentService>();
return services;
}
}
// Usage in Program.cs:
builder.Services.AddPaymentServices(builder.Configuration);실전 예제: 여러 제공업체를 사용하는 알림
팩토리와 이름 있는 옵션을 함께 사용하면 데이터베이스에 저장된 사용자 설정에 따라 런타임에 적절한 알림 제공업체를 선택할 수 있습니다.
builder.Services.AddKeyedScoped<INotifier, EmailNotifier>("email");
builder.Services.AddKeyedScoped<INotifier, SmsNotifier>("sms");
builder.Services.AddKeyedScoped<INotifier, PushNotifier>("push");
public class NotificationService
{
private readonly IServiceProvider _sp;
public NotificationService(IServiceProvider sp) => _sp = sp;
public Task SendAsync(string channel, string message)
{
var notifier = _sp.GetRequiredKeyedService<INotifier>(channel);
return notifier.SendAsync(message);
}
}빠른 확인
현재 옵션 값을 제공하고 구성 변경 시 알림도 보내므로 싱글턴 서비스에 적합한 인터페이스는 무엇인가요? AND
복습: 팩토리 및 옵션 패턴
핵심 요점:
Add*메서드의 팩토리 대리자를 사용하면 조건에 따른 서비스 생성이나 런타임 구성에 따른 서비스 생성을 지원할 수 있습니다- 옵션 패턴은 구성 섹션을 강한 형식의 일반 객체에 바인딩합니다
IOptions= 정적,IOptionsSnapshot= 요청마다 갱신,IOptionsMonitor= 실시간 업데이트ValidateDataAnnotations().ValidateOnStart()로 시작 시 옵션을 검증합니다- 키 기반 서비스(.NET 8)는 이름 있는 구현을 위한 팩토리 우회 방법을 대체합니다
AI 튜터와 함께 C#을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 93
- 레슨
- 346
자주 묻는 질문
“팩터리와 옵션 패턴” 강의는 무료인가요?
네 — “팩터리와 옵션 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C# Academy 강의 전체를 잠금 해제할 수 있습니다. C# Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“팩터리와 옵션 패턴”에서 뭘 배우나요?
팩터리 대리자, IServiceProvider, Options 패턴을 사용해 조건부 또는 구성 가능한 의존성을 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 C# Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
C# Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 C# Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“팩터리와 옵션 패턴” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 C# Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 C# Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.