Advertisement
Intermediate ASP.NET Core, Dependency Injection

How do you register a service using a factory delegate instead of a simple type mapping, when construction requires reading configuration or resolving other services conditionally?

Short answer

AddScoped/AddSingleton/AddTransient overloads accept a factory delegate (IServiceProvider sp) => new MyService(...), letting you perform custom construction logic -- like reading a configuration value to conditionally choose an implementation -- that a simple type-to-type…

Save ASP.NET Core mock interview
Advertisement
AModel answer
AddScoped/AddSingleton/AddTransient overloads accept a factory delegate (IServiceProvider sp) => new MyService(...), letting you perform custom construction logic -- like reading a configuration value to conditionally choose an implementation -- 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