Advertisement
Intermediate .NET, Dependency Injection

How do you register a service using a factory delegate instead of a simple type mapping, when construction requires custom logic?

Short answer

AddScoped/AddSingleton/AddTransient overloads accept a factory delegate `(IServiceProvider sp) => new MyService(...)` letting you perform custom construction logic -- like resolving other services manually, reading configuration values, or choosing an implementation…

Save .NET mock interview
Advertisement
AModel answer
AddScoped/AddSingleton/AddTransient overloads accept a factory delegate `(IServiceProvider sp) => new MyService(...)` letting you perform custom construction logic -- like resolving other services manually, reading configuration values, or choosing an implementation conditionally -- that a simple type-to-type registration can't express.
builder.Services.AddScoped<IPaymentGateway>(sp => {
    var config = sp.GetRequiredService<IOptions<PaymentSettings>>().Value;
    return config.Provider switch {
        "stripe" => new StripeGateway(config.ApiKey),
        "paypal" => new PayPalGateway(config.ApiKey),
        _ => throw new InvalidOperationException("Unknown payment provider")
    };
});
Real-world example
A payment processing service chooses its concrete gateway implementation dynamically based on a configuration value at registration time, using a factory delegate since the simple AddScoped<TInterface, TImplementation> overload can't express this conditional logic.
Likely follow-ups
  • How does this compare to using keyed services for the same conditional-provider scenario?
  • What services can you safely resolve inside a factory delegate without lifetime issues?
Related topics