In ASP.NET Core, when does a registration need a factory lambda or ActivatorUtilities.CreateInstance instead of a type mapping, and what does each cost?
answer
- a constructor argument that is not a service
- Func<IServiceProvider, T> sees the resolving scope
- CreateInstance(provider, params object[])
- [ActivatorUtilitiesConstructor] pins the constructor
- validation cannot see inside a lambda
basics
~20 sUse a factory lambda when construction needs runtime values, configuration-driven choice or forwarding; use ActivatorUtilities.CreateInstance inside it to pass the extra values while the container fills the remaining parameters. The cost: hand-written construction the container cannot validate or inspect.
solid answer
~40 sA type mapping like `AddScoped<IPaymentGateway, StripeGateway>()` works only when every constructor parameter is a registered service. When `StripeGateway` also needs a value such as the API key for its merchant account, register a **factory**: `AddScoped<IPaymentGateway>(sp => ...)`; keyed factories also receive the key. Writing `new StripeGateway(key, sp.GetRequiredService<...>(), ...)` by hand breaks every time the constructor changes, so call `ActivatorUtilities.CreateInstance<StripeGateway>(sp, apiKey)`: it uses `apiKey` for the matching parameter and resolves the rest from `sp`. The costs: the container cannot see what a lambda resolves, so `ValidateOnBuild` does not check it; the implementation type is hidden, so `TryAddEnumerable` cannot deduplicate it; and open generics cannot use factories. Never call `BuildServiceProvider()` to get a dependency during registration; use the lambda's `sp`.
code
csharp · 14 linesbuilder.Services.AddKeyedScoped<IPaymentGateway>("stripe", (sp, key) =>
{
var opts = sp.GetRequiredService<IOptionsMonitor<GatewayOptions>>()
.Get((string)key!);
return ActivatorUtilities.CreateInstance<StripeGateway>(sp, opts.ApiKey);
});
public sealed class StripeGateway(
string apiKey,
IHttpClientFactory http,
ILogger<StripeGateway> log) : IPaymentGateway
{
public string Name => "stripe";
}go deeper
Recall that a registration can take a lambda receiving IServiceProvider, and that it is used when a constructor needs something that is not a service.
Explain the lambda's sp parameter, the keyed factory overload, and what ActivatorUtilities.CreateInstance does with explicit arguments versus resolved ones.
Weigh the costs: lost validation, hidden implementation type, no open generics, constructor drift. Know the BuildServiceProvider anti-pattern and when CreateFactory pays off.
Set team conventions for where construction logic lives, factories versus options or dedicated factory classes, so the object graph stays verifiable at startup.
## What a type mapping cannot express With `AddScoped<IPaymentGateway, StripeGateway>()` the container picks a public constructor and resolves **every** parameter from the container. That fails when a parameter is not a service: - a value from configuration or a database, such as the API key for the marketplace's merchant account with each provider; - a decision made at registration time, such as choosing a sandbox or live implementation from a setting; - an object that must be produced by a builder or a static factory method; - **forwarding**: making two interfaces share one instance, `AddSingleton<IRefundSource>(sp => sp.GetRequiredService<PayoutLedger>())`. ## Factory lambdas A factory registration takes `Func<IServiceProvider, TService>`; the keyed overloads take `Func<IServiceProvider, object?, TService>` and receive the key too. The `sp` argument is the provider doing the resolving: the request scope for a scoped service, the root provider for a singleton. The lambda runs whenever the lifetime needs a new instance. Costs to weigh: 1. **The container cannot see inside.** `ValidateOnBuild` checks that a factory registration exists, not what the lambda resolves, so a missing dependency surfaces on the first request instead of at startup. 2. **The implementation type is hidden.** A factory typed `Func<IServiceProvider, IPaymentGateway>` reports `IPaymentGateway` as its implementation, so `TryAddEnumerable` throws `ArgumentException` for it. Use the two-type form, such as `ServiceDescriptor.Scoped<IPaymentGateway, StripeGateway>(sp => ...)`. 3. **No open generics.** An open generic registration requires an implementation type. 4. **Hand-written `new`** has to change with every constructor change. One anti-pattern deserves its own warning: calling `builder.Services.BuildServiceProvider()` during registration to obtain a dependency. It builds a second container with its own singletons. The ASP0000 analyzer's message says it "results in an additional copy of singleton services being created". The lambda's `sp` is always the right provider. ## ActivatorUtilities: mixing explicit arguments with services `ActivatorUtilities` (namespace `Microsoft.Extensions.DependencyInjection`) builds a type that is **not registered** by combining arguments you pass with services from a provider: | Member | Use | |---|---| | `CreateInstance<T>(provider, params object[] parameters)` | one instance; explicit arguments fill matching parameters, the rest are resolved | | `CreateFactory<T>(Type[] argumentTypes)` | returns an `ObjectFactory<T>` delegate to call many times, avoiding repeated constructor matching | | `GetServiceOrCreateInstance<T>(provider)` | resolves `T` if registered, otherwise constructs it | | `[ActivatorUtilitiesConstructor]` | marks the constructor to use when several could match | When several constructors could match, `CreateInstance` prefers the longest one whose parameters are covered by the given arguments, registered services or default values. Two equally long candidates throw, and so do two constructors marked with the attribute. ASP.NET Core uses the same helper itself: `UseMiddleware<T>(args)` creates middleware with `ActivatorUtilities.CreateInstance`, and MVC creates controllers through `ActivatorUtilities.CreateFactory`, which is why controllers do not need registering. ## Putting them together The marketplace's gateways each need their own credentials: ```csharp builder.Services.AddKeyedScoped<IPaymentGateway>("stripe", (sp, key) => { var opts = sp.GetRequiredService<IOptionsMonitor<GatewayOptions>>().Get((string)key!); return ActivatorUtilities.CreateInstance<StripeGateway>(sp, opts.ApiKey); }); ``` The lambda supplies the one value the container cannot know, and `ActivatorUtilities` resolves the gateway's logger and `IHttpClientFactory`, so a new constructor dependency needs no change here. Because the lambda is registered, the container tracks and disposes what it returns. An object created with `CreateInstance` **outside** a registration belongs to the caller, who must dispose it. ## Errors you will meet | Message (abridged) | Cause | |---|---| | "A suitable constructor for type '...' could not be located" | a parameter is neither a registered service, a passed argument, nor optional | | "Multiple constructors for type '...' were found with length ..." | two equally long constructors both match; mark one with `[ActivatorUtilitiesConstructor]` | | "Multiple constructors were marked with ActivatorUtilitiesConstructorAttribute" | the attribute is on more than one constructor | | "Instances of abstract classes cannot be created" | an interface or abstract class was passed as the type to create | `ActivatorUtilities` gives each explicit argument to the first unfilled parameter whose type accepts it. With two parameters of the same type, such as an API key and a webhook secret, the values are assigned in argument order, so a call that swaps them compiles and runs with the credentials crossed. Wrap such values in one small options object instead. Rule of thumb: prefer a type mapping, add a factory only for what the container cannot know, and let `ActivatorUtilities` do the constructor work.
- When would you choose ActivatorUtilities.CreateFactory over CreateInstance?When the same type is built many times with different explicit arguments, for example a handler per incoming message. `CreateFactory<T>(argumentTypes)` matches the constructor once and returns an `ObjectFactory<T>` delegate; each call then passes the provider and the argument array, skipping the constructor search that `CreateInstance` repeats every time.
- Why do MVC controllers resolve their dependencies even though they are never registered in the container?MVC activates controllers through a type activator that uses `ActivatorUtilities.CreateFactory`, so constructor parameters come from the request's services while the controller type itself stays unregistered. Calling `AddControllersAsServices()` changes that and registers controllers so the container creates them.
- Call builder.Services.BuildServiceProvider() inside registration to fetch a dependency for a factory.
- ValidateOnBuild verifies every service a factory lambda resolves.
- ActivatorUtilities.CreateInstance only works for types registered in the container.
- ActivatorUtilities.CreateInstance needs every constructor argument passed explicitly.
- The container never disposes objects returned by a registered factory lambda.