How would you implement the Factory pattern using dependency injection to resolve a specific implementation at runtime based on a parameter, when the standard container can't decide statically?
Short answer
Inject a factory delegate (Func ) or a dedicated factory interface/class instead of the service directly — the factory itself is registered normally in DI, and its implementation resolves the correct concrete service (often via a keyed lookup among several registered…
Advertisement
AModel answer
Inject a factory delegate (Func<string, IService>) or a dedicated factory interface/class instead of the service directly — the factory itself is registered normally in DI, and its implementation resolves the correct concrete service (often via a keyed lookup among several registered implementations) at the moment it's actually needed, based on runtime information the container itself doesn't have.
public interface IPaymentProcessorFactory { IPaymentProcessor Create(string provider); }
public class PaymentProcessorFactory : IPaymentProcessorFactory {
private readonly IEnumerable<IPaymentProcessor> _processors;
public PaymentProcessorFactory(IEnumerable<IPaymentProcessor> processors) { _processors = processors; }
public IPaymentProcessor Create(string provider) =>
_processors.First(p => p.ProviderName == provider);
}Real-world example
Selecting between multiple registered payment gateway implementations (Stripe, PayPal, etc.) at runtime based on a user's chosen provider.
Likely follow-ups
- How does .NET 8's newer KEYED SERVICES feature (AddKeyedSingleton, etc.) simplify this exact pattern natively?
Related topics