Factory & Options Patterns
Use factory delegates, IServiceProvider, and the Options pattern to handle conditional or configurable dependencies.
When Constructor Injection Isn't Enough
Sometimes you need to create services conditionally, based on runtime data, or configure them differently per use case. That's where factory patterns and the Options pattern shine.
Factory Delegates with AddTransient
You can pass a factory delegate to AddTransient, AddScoped, or AddSingleton. The delegate receives IServiceProvider so you can resolve other services.
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);
});