skip to content

Keyed & Open Generic Types

IServiceCollection decides what a resolve returns: TryAdd skips duplicates, the last registration wins, and keyed or open generic registrations pick an implementation. Interviewers test these rules.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core, when IPaymentGateway is registered twice with AddScoped, what does constructor injection receive, and what does IEnumerable<IPaymentGateway> receive?

level: juniorimportance: must knowfreq 62%

answer

  1. registration is a list append
  2. no error on a duplicate
  3. descriptor order decides the single resolve
  4. IEnumerable<T> sees the whole list
  5. keyed descriptors stay out

basics

~10 s

Constructor injection of IPaymentGateway gets the implementation from the last AddScoped call; IEnumerable<IPaymentGateway> gets one instance of every unkeyed registration, in registration order. The container raises no error about the duplicate.

solid answer

~40 s

`IServiceCollection` is a list of `ServiceDescriptor`s, so a second `AddScoped<IPaymentGateway, PayPalGateway>()` does not replace the first one: it appends. When a constructor asks for a single `IPaymentGateway`, the built-in container uses the **last** descriptor registered for that service type. When it asks for `IEnumerable<IPaymentGateway>`, the container builds one instance per registration, in the order they were added. Nothing warns about the duplicate, so an accidental second registration silently changes which gateway a service receives. Injecting `IEnumerable<T>` is the intended way to get all implementations, for example every payment provider a checkout page lists. Keyed registrations made with `AddKeyedScoped` form a separate set: neither the single resolve nor the unkeyed `IEnumerable<T>` returns them.

code

csharp · 13 lines
csharp
builder.Services.AddScoped<IPaymentGateway, StripeGateway>();
builder.Services.AddScoped<IPaymentGateway, PayPalGateway>();
builder.Services.AddScoped<IPaymentGateway, AdyenGateway>();
builder.Services.AddScoped<CheckoutSummary>();

public sealed class CheckoutSummary(
    IPaymentGateway single,
    IEnumerable<IPaymentGateway> all)
{
    public string Chosen => single.Name;               // "adyen"
    public IReadOnlyList<string> Offered =>
        all.Select(g => g.Name).ToList();             // stripe, paypal, adyen
}

go deeper

for a junior

Recall the two rules: a single resolve gets the last registration, IEnumerable<T> gets every registration in order. Say that a duplicate raises no error.

for a middle

Explain that IServiceCollection is a list of descriptors, why last-wins lets an app override a library default, and that keyed registrations sit outside both lookups.

for a senior

Show how a stray second registration changes behaviour silently in production, and how you guard against it: per-order selection instead of a single injected gateway, and a test that counts descriptors.

for a principal

Frame registration order as an implicit contract between modules and libraries; argue for explicit selection (keys or a resolver) over relying on which assembly registered last.

## The collection is a list, not a dictionary `IServiceCollection` is an ordered list of **service descriptors**. Each `AddScoped<TService, TImplementation>()` call creates a `ServiceDescriptor` (service type, implementation, lifetime, optional key) and appends it. Nothing checks whether that service type is already present, so registering `IPaymentGateway` twice gives two descriptors and no exception, at registration time or at `builder.Build()`. The duplicate matters only when something is resolved, and the answer depends on how the consumer asks. ## What a single resolve returns When a constructor parameter, `GetRequiredService<IPaymentGateway>()` or any other single-service request asks for `IPaymentGateway`, the built-in container looks up every descriptor for that exact type and uses the **last** one. The rule is often called **last registration wins**: ```csharp builder.Services.AddScoped<IPaymentGateway, StripeGateway>(); builder.Services.AddScoped<IPaymentGateway, PayPalGateway>(); builder.Services.AddScoped<IPaymentGateway, AdyenGateway>(); // a constructor asking for IPaymentGateway receives AdyenGateway ``` This is what lets an application override a default that a library registered earlier: add your own implementation after the library's `AddX()` call and yours is the one consumers get. ## What IEnumerable<T> returns The container treats `IEnumerable<T>` specially: you never register it, yet you can always inject it. It contains **one instance per unkeyed registration of `T`, in registration order**. For the three registrations above it holds a `StripeGateway`, a `PayPalGateway` and an `AdyenGateway`, in that order. If `T` has no registration at all, you get an empty sequence instead of an exception. | Consumer asks for | Result with three registrations | |---|---| | `IPaymentGateway` | the last one, `AdyenGateway` | | `IEnumerable<IPaymentGateway>` | all three, in registration order | | `IEnumerable<IPaymentGateway>` with none registered | an empty sequence | | `IPaymentGateway` with none registered | constructor injection fails with `InvalidOperationException`; `GetService` returns `null` | For scoped and singleton registrations, the last item of the sequence and the single-resolve instance are the **same object** inside one scope, because the container caches them in the same slot. Transient registrations give a new object each time. ## Where it bites: the artisan marketplace Picture a marketplace where makers sell pottery and textiles, and checkout supports Stripe, PayPal and Adyen. - A `PaymentOptionsPage` that lists every provider should inject `IEnumerable<IPaymentGateway>` and loop over it. - A `RefundService` that injects a single `IPaymentGateway` gets only `AdyenGateway`, which is almost never what the author meant. Refunds must go back through the provider that took the payment, so the code needs to choose a gateway per order, not take whichever one was registered last. - A feature module that registers `IPaymentGateway` again, say in a test-friendly fake left in by mistake, silently replaces the real gateway for every single-service consumer. ## Framework defaults follow the same rule The same rule lets you override services that ASP.NET Core itself registers. `AddProblemDetails()` registers `IProblemDetailsService` with `TryAddSingleton`; if you call `AddSingleton<IProblemDetailsService, MarketplaceProblemDetailsService>()` after it, a single resolve returns yours because it is last. Two consequences are easy to miss: - consumers that inject `IEnumerable<T>` of a framework service still see **both** implementations, so a pipeline that runs every registered writer or setup runs the framework's one too; - an override registered **before** the framework's `AddX()` call survives only if the framework used `TryAdd`; with a plain `Add` the framework's later registration wins. When a resolve returns something unexpected, list the descriptors instead of guessing: `builder.Services.Where(d => d.ServiceType == typeof(IPaymentGateway))` shows every registration with its implementation type and lifetime, in the order the container will use. ## Making intent explicit Three tools from the same API remove the guesswork: 1. **`TryAdd*`** registers only when nothing is registered for the service type yet. Library authors use it so an application's earlier registration is kept. 2. **Keyed services** (`AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe")`, since .NET 8) let a caller ask for a specific implementation by key. Keyed descriptors are not part of the unkeyed `IEnumerable<IPaymentGateway>`, and a plain `IPaymentGateway` request does not see them. 3. **Inspecting the collection** in a unit test, for example `builder.Services.Count(d => d.ServiceType == typeof(IPaymentGateway))`, catches an accidental double registration before it reaches production. The model to remember: registration appends, a single resolve takes the last descriptor, and the enumerable takes all of them.

  • Within one request, is the last item of IEnumerable<IPaymentGateway> the same object as an injected IPaymentGateway?
    For scoped and singleton registrations, yes. The built-in container caches the last registration and the single-service resolve in the same slot, so both point at one `AdyenGateway` instance within the scope. Earlier items are separate instances. With transient registrations every resolve, including each enumeration, creates new objects.
  • How would you catch an accidental duplicate registration before production?
    Assert on the collection in a unit test: build the same `IServiceCollection` your `Program.cs` builds and check `services.Count(d => d.ServiceType == typeof(IPaymentGateway))`. Alternatively resolve `IEnumerable<IPaymentGateway>` from the built provider and assert its length. The container itself will never report the duplicate, because two descriptors for one type are legal.

Registrations are names written on one sign-up sheet. Ask the organiser for the volunteer and you get the last name written; ask for all volunteers and you get the whole sheet, top to bottom. Writing a name twice is never refused.

  • Registering the same interface twice makes builder.Build() throw at startup.
  • With two AddScoped calls, the first registration wins and the second is ignored.
  • IEnumerable<IPaymentGateway> returns only the most recently registered implementation.
  • AddScoped removes any earlier registration of the same service type.
  • IEnumerable<IPaymentGateway> also includes the AddKeyedScoped registrations.
open as a page

In ASP.NET Core 10, how do you choose among three keyed IPaymentGateway registrations per request, and what can go wrong with the key?

level: middleimportance: must knowfreq 54%

basics

~10 s

Register each gateway with AddKeyedScoped<IPaymentGateway, T>(key), then resolve at runtime with GetRequiredKeyedService<IPaymentGateway>(order.Provider) from the request's IServiceProvider. Keys match by Equals, so case or type mismatches throw InvalidOperationException.

open as a page

In ASP.NET Core, how do you register IRepository<T> once for every entity with an open generic, and when does a closed registration take over?

level: middleimportance: should knowfreq 42%

basics

~10 s

Register services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>)); the container closes EfRepository<T> for each requested T. A closed registration such as IRepository<Order> wins for that type regardless of order, because exact matches are tried first.

open as a page

In ASP.NET Core, how do TryAddScoped, TryAddEnumerable, Replace and RemoveAll differ from a plain AddScoped, and why do library AddX methods use them?

level: middleimportance: should knowfreq 44%

basics

~20 s

TryAddScoped adds only when the service type has no registration yet; TryAddEnumerable skips only an identical implementation type; Replace swaps the first matching registration; RemoveAll deletes every unkeyed one. Libraries use TryAdd so app registrations survive and AddX stays idempotent.

open as a page

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?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Use 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.

open as a page