📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does the built-in .NET container handle open generic registrations such as AddScoped(typeof(IValidator<>), typeof(Validator<>))? Explain when the type gets closed, how a closed registration overrides the open one, what happens with generic constraints and IEnumerable<T>, and what you cannot do with open generics in Microsoft.Extensions.DependencyInjection.

How Microsoft.Extensions.DependencyInjection closes open generic registrations at resolution time, closed-over-open precedence, constraint handling, IEnumerable mixing, per-closed-type lifetimes and the limits (no factories, no partial closing, skipped by ValidateOnBuild).

Mid-Level Theory Intermediate aspnet-core dependency-injection generics open-generics service-registration

🎯 Key points

  • An open generic descriptor is closed lazily with MakeGenericType the first time a closed service type is requested
  • Exact (closed) registrations are tried before open generics, so a closed registration wins regardless of order
  • IEnumerable<IValidator<Order>> returns closed and open matches together, in registration order
  • Every lifetime applies per closed type: one singleton per T, one scoped instance per T per scope, a new transient per T per resolution
  • Constrained open generics (.NET 5+): implementations whose constraints fail are skipped in IEnumerable resolution
  • No implementation factory and no instance for open generics; arity and parameter order must match
  • Constructor dependencies of the closed implementation (including ones built from T) are only checked at first resolution
  • ValidateOnBuild skips open generic descriptors, so test-resolve every closed type you use in a composition-root test

⏱ 30-second answer

An open generic registration stores a descriptor whose service and implementation types are generic type definitions. Nothing is built at registration time: the first time someone asks for IValidator<Order>, the container's CallSiteFactory looks for an exact closed registration first, then closes the open one with MakeGenericType(typeof(Order)), builds a call site and caches it. That ordering means a closed registration always overrides the open one, while IEnumerable<IValidator<Order>> returns both. Lifetimes apply per closed type, so a singleton open generic gives one instance per T. Implementations whose generic constraints don't fit are skipped when enumerating. The limits: no factory delegates for open generics, no partial closing, and ValidateOnBuild can't check them. The trade-off is a big cut in registration code, paid for with errors that only appear at first resolution.

🗣 Full answer (senior)

How I would answer this in an interview

"An open generic registration is a descriptor where both types are generic type definitions, like typeof(IRepository<>) and typeof(EfRepository<>). The container doesn't do anything with it at registration time. When something asks for IRepository<Order>, the CallSiteFactory first looks for an exact registration of the closed type. If there isn't one, it walks the open generic descriptors, calls MakeGenericType with Order, builds a call site for EfRepository<Order> and caches it, so the reflection cost is paid once per closed type.

Two rules come out of that lookup order. First, a closed registration like IRepository<AuditLog> → AuditLogRepository wins over the open one no matter which was registered first, which is how I special-case one entity. Second, IEnumerable<IValidator<Order>> collects every match, closed and open, in registration order, and since .NET 5 it skips open implementations whose generic constraints don't fit Order. Lifetimes apply per closed type: a singleton ICache<> gives you one Cache<Order> and a separate Cache<Customer>.

The mistake I see is assuming the container validates all of this at start-up. ValidateOnBuild skips open generic descriptors because it has no type argument to try, so a missing dependency of EfRepository<T> only blows up on the first request that needs it. I add an integration test that resolves the closed types we actually use. Open generics remove a lot of registration noise, but the price is that errors move from start-up to first use, so I test the composition root."


How resolution picks an implementation

Request What the container does
GetService<IRepository<Order>>() Exact closed registration? Use the last one. Otherwise close the last matching open generic
GetServices<IValidator<Order>>() All closed and open matches, in registration order; open ones with unmet constraints are skipped
IRepository<int> when EfRepository<T> where T : class Constraint violation: no valid implementation, resolution fails
Singleton ICache<> One instance per closed type, cached in the root scope

What you can and cannot do

Supported Not supported in the built-in container
AddScoped(typeof(IX<>), typeof(X<>)) AddScoped(typeof(IX<>), sp => ...) (no factory for open generics)
Multiple type parameters with the same arity and order (IHandler<,> → Handler<,>) Partially closed types (IX<T> → X<T, string>) or reordered parameters
Constrained implementations (where T : IEntity) Conditional registration based on T beyond constraints
Closed overrides of an open registration Decorating an open generic without a library (Scrutor) or hand-written closing
Keyed open generics (AddKeyedScoped(typeof(IX<>), key, typeof(X<>))) Validation at build time

When to use / when not

Use open generics when Avoid them when
The behaviour is truly identical for every T (validators pipeline, ILogger<T>, IOptions<T>) Most Ts need special cases: you end up with many closed overrides and confusing precedence
The framework already does it (ILogger<>, IOptions<> are open generic registrations) You need a factory per type: register closed types instead
You test resolution of the closed types you use You publish Native AOT with value-type arguments and can't test every closed type

Production example

In a claims service we had about 140 FluentValidation-style validators and an IValidator<> open generic fallback that returned "no rules". One NullValidator<T> registered as open plus closed registrations by assembly scanning cut Program.cs from roughly 300 lines of registrations to 20. The first week it hid a bug: a renamed validator stopped being registered, the open NullValidator<T> silently took over, and invalid claims got through. We added a test asserting every request type resolves a non-null-object validator, which caught two more gaps.

🔍 What the interviewer is checking

Checks whether the candidate understands how the built-in container resolves open generics rather than just knowing the typeof(IX<>) syntax.

Green flags

  • Explains lazy closing with MakeGenericType at first resolution and caching per closed type
  • States closed-over-open precedence and how IEnumerable<T> mixes both
  • Knows open generics can't use factories and aren't checked by ValidateOnBuild
  • Mentions constraint filtering and per-closed-type singletons

Red flags

  • Thinks the last registration always wins regardless of open or closed
  • Believes a singleton open generic is one shared object
  • Has never tested resolution of the closed types

📚 Learn in depth

1. What a descriptor for an open generic looks like

ServiceDescriptor stores ServiceType, ImplementationType (or a factory or instance) and Lifetime. For an open generic both types have IsGenericTypeDefinition == true. Because there is no type argument yet, the container cannot build a call site at registration or build time.

IServiceCollection
  [0] IValidator<>        -> NullValidator<>        (Scoped)   open
  [1] IValidator<Order>   -> OrderValidator         (Scoped)   closed
  [2] IRepository<>       -> EfRepository<>         (Scoped)   open

2. The lookup order in CallSiteFactory

When a service type is requested for the first time, CallSiteFactory.CreateCallSite tries, in order:

1. TryCreateExact        -> closed descriptors for exactly this type (last one wins)
2. TryCreateOpenGeneric  -> if the type is a constructed generic, look up descriptors
                            for its generic type definition, close the implementation
                            with MakeGenericType(args), then build a constructor call site
3. TryCreateEnumerable   -> for IEnumerable<T>: gather ALL closed and open matches

The resulting call site is cached in a dictionary keyed by the service identifier (type plus optional key), and the engine later compiles it (expression trees or IL emit, after a couple of resolutions) into a fast delegate. So the MakeGenericType reflection runs once per closed type, not once per request.

3. Constraints

If EfRepository<T> where T : class, IEntity is registered for IRepository<>, closing it with int would make MakeGenericType throw. Since .NET 5 (the "constrained open generics" change) the enumerable path checks constraints and simply skips implementations that can't be closed. That lets you register several open validators with different constraints (where T : IHasAddress, where T : IHasEmail) and get only the relevant ones in IEnumerable<IValidator<T>>. For a single-service resolution, an unsatisfied constraint means there is no usable implementation, and you get a resolution failure rather than a wrong object.

4. Lifetimes per closed type

Each closed type has its own call site and its own cache slot:

singleton ICache<>  ->  Cache<Order>     (instance A, root scope)
                    ->  Cache<Customer>  (instance B, root scope)

A captive dependency check (ValidateScopes) still runs at resolution time for each closed type, so a singleton open generic that depends on a scoped service is caught the first time that closed type is resolved in Development.

5. Why ValidateOnBuild can't help

ValidateOnBuild iterates descriptors and builds a call site for each. For open generic descriptors there is no type argument to try, so they are skipped. Unknown closed types that will be requested later are, by definition, unknown at build time. The fix is a test that enumerates the types you actually use (for example all entity types in your DbContext model or all request types in an assembly) and resolves the closed service.

6. Native AOT

Closing a generic over a reference type can share canonical code, which Native AOT can precompile. Closing over a value type needs a specialised instantiation the AOT compiler may not have generated. The DI library guards this and can throw at run time for value-type closed generics or enumerables under AOT. In AOT apps, keep type arguments as reference types or register closed types explicitly.

7. Variations in other containers

Autofac and Lamar support factories for open generics, conditional open-generic registration and native decorators. Scrutor adds Decorate(typeof(IX<>), typeof(Decorator<>)) on top of the built-in container. The built-in container intentionally keeps the minimal feature set that ASP.NET Core itself needs.

Try it yourself

  1. Register IRepository<> → EfRepository<> and a closed IRepository<AuditLog> before it. Resolve both closed types and print the implementation names to confirm closed-over-open precedence.
  2. Register two open validators with different constraints and resolve IEnumerable<IValidator<Order>>; check which ones appear.
  3. Turn on ValidateOnBuild, give EfRepository<T> an unregistered constructor dependency, and observe that Build() succeeds and the first resolution fails.
  4. Write an xUnit test that reflects over your DbContext model's entity types and resolves IRepository<T> for each.
  5. Use BenchmarkDotNet to compare the first and the 1,000th resolution of a closed open-generic service.

💻 Code

Open generic registrations, a closed override and constraint-filtered enumeration (.NET 10, C# 14):

using Microsoft.Extensions.DependencyInjection;

namespace Claims.Validation;

public interface IValidator<in T> { IEnumerable<string> Validate(T item); }
public interface IHasEmail { string Email { get; } }

// Applies to every T: a fallback that adds no errors.
public sealed class NoRulesValidator<T> : IValidator<T>
{
    public IEnumerable<string> Validate(T item) => [];
}

// Only closes for T that implements IHasEmail; skipped for other T in IEnumerable resolution.
public sealed class EmailValidator<T> : IValidator<T> where T : IHasEmail
{
    public IEnumerable<string> Validate(T item) =>
        item.Email.Contains('@') ? [] : ["Email is invalid."];
}

public sealed record Customer(string Email) : IHasEmail;
public sealed record Invoice(decimal Total);

public sealed class InvoiceValidator : IValidator<Invoice>
{
    public IEnumerable<string> Validate(Invoice item) =>
        item.Total >= 0 ? [] : ["Total cannot be negative."];
}

public static class Program
{
    public static void Main()
    {
        var services = new ServiceCollection();
        services.AddScoped(typeof(IValidator<>), typeof(NoRulesValidator<>)); // open
        services.AddScoped(typeof(IValidator<>), typeof(EmailValidator<>));   // open, constrained
        services.AddScoped<IValidator<Invoice>, InvoiceValidator>();          // closed

        using var provider = services.BuildServiceProvider(
            new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true });
        using var scope = provider.CreateScope();

        // Single resolution: closed registration wins even though it was added last.
        Console.WriteLine(scope.ServiceProvider.GetRequiredService<IValidator<Invoice>>().GetType().Name);
        // -> InvoiceValidator

        // Enumeration: NoRulesValidator<Customer> and EmailValidator<Customer>.
        foreach (var v in scope.ServiceProvider.GetServices<IValidator<Customer>>())
            Console.WriteLine(v.GetType().Name);

        // Enumeration for Invoice: EmailValidator<Invoice> is skipped (constraint not met).
        foreach (var v in scope.ServiceProvider.GetServices<IValidator<Invoice>>())
            Console.WriteLine(v.GetType().Name); // NoRulesValidator`1, InvoiceValidator
    }
}

A composition-root test that covers what ValidateOnBuild cannot:

[Fact]
public void Every_request_type_resolves_a_validator()
{
    using var provider = TestHost.BuildServices();
    using var scope = provider.CreateScope();
    var requestTypes = typeof(Customer).Assembly.GetTypes()
        .Where(t => t is { IsClass: true, IsAbstract: false } && t.Name.EndsWith("Request"));

    foreach (var type in requestTypes)
    {
        var serviceType = typeof(IValidator<>).MakeGenericType(type);
        Assert.NotNull(scope.ServiceProvider.GetService(serviceType));
    }
}

⚠ Common mistakes

  • Mistake: Expecting registration order to decide between a closed and an open registration. Why it is wrong: exact closed registrations are always tried first. Instead: rely on closed-over-open precedence, and document it next to the registration.
  • Mistake: Trying services.AddScoped(typeof(IRepo<>), sp => ...). Why it is wrong: the built-in container rejects factories for open generics. Instead: put the logic in the implementation's constructor, register closed types, or use another container.
  • Mistake: Assuming ValidateOnBuild covers open generics. Why it is wrong: open descriptors are skipped, so a missing constructor dependency of EfRepository<T> (for example an unregistered IAuditSink<T>) only throws InvalidOperationException: Unable to resolve service on the first request that needs that closed type. Instead: write a test that resolves each closed type you use.
  • Mistake: Thinking a singleton open generic is a single shared instance. Why it is wrong: there is one instance per closed type, so Cache<Order> and Cache<Customer> never share state. Instead: if you need one shared object, register a non-generic singleton and inject it.
  • Mistake: Registering an open "null object" fallback (IValidator<> → NoRulesValidator<>) and assuming real validators will always win. Why it is wrong: the real validators win only if they are registered. If one is renamed, moved out of a scanned namespace or deleted, resolution of IValidator<CreateOrder> quietly closes the fallback instead, no exception is thrown, and invalid requests are accepted. Instead: assert in tests that every request type resolves its real implementation, and log or count fallback resolutions in production.
  • Mistake: Partially closing or reordering type parameters (IMap<TIn, TOut> → Mapper<TOut, TIn>). Why it is wrong: the container closes by position and needs the same arity. Instead: make the implementation's parameters mirror the service's.
  • Mistake: Using open generics with value-type arguments in a Native AOT app without testing. Why it is wrong: the required instantiation may not exist and resolution throws at run time. Instead: use reference types or closed registrations and run AOT smoke tests.

🏛 Senior insight: trade-offs

Open generics are worth it when the behaviour is identical across T and the framework already models it that way (ILogger<>, IOptions<>, a validation pipeline). The senior move is knowing that the convenience shifts errors from start-up to first use, and paying that back with a composition-root test. If you find yourself adding more closed overrides than types that use the open default, the abstraction is wrong: register closed types or rethink the generic.

Option When it fits Cost When not to
Open generic registration Uniform behaviour for many T Errors at first resolution; no factories Many special cases per T
Closed registrations via scanning (Scrutor) Many concrete implementations Start-up reflection; library dependency Native AOT apps (reflection scanning)
Explicit closed registrations Few types, AOT, maximum clarity More lines in Program.cs Hundreds of types
Another container (Autofac) Need open-generic factories or conditions Extra dependency and learning Only for one feature you can live without

Measure with a startup trace (dotnet-trace with the Microsoft-Extensions-DependencyInjection event source) if you suspect resolution cost; in practice the first-resolution cost per closed type is microseconds and rarely matters.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions generic repositories or decorating open generics Why: Checks deeper generics knowledge and the limits of the built-in container with open generic decorators
    How to answer

    You register the open types, services.AddScoped(typeof(IRepository<>), typeof(Repository<>)), and when someone asks for IRepository<Order> the container closes the implementation with MakeGenericType and builds it, caching that plan. An exact closed registration for IRepository<Order> wins over the open one, while IEnumerable<IRepository<Order>> returns both. Lifetimes are per closed type. Microsoft DI has no decorator support, so I use Scrutor's Decorate for open generics or write it by hand. ValidateOnBuild cannot check open generics, so I add tests that resolve real closed types.

  2. When: Candidate says ValidateOnBuild will catch registration mistakes Why: Checks whether they know which descriptors ValidateOnBuild skips
    How to answer

    ValidateOnBuild makes Build() walk every registration and try to build its call site, so a missing dependency or an unresolvable constructor fails at start-up instead of on the first request that needs it. Combined with ValidateScopes it also catches a singleton depending on a scoped service.

    What it cannot catch:

    • anything inside a factory delegate (sp => ...): the body is opaque code that only runs on resolution;
    • open generics, which can't be checked until a closed type is requested;
    • types created later with ActivatorUtilities.CreateInstance or GetService calls in your own code.

    ASP.NET Core's WebApplication turns it on only in the Development environment; enable it everywhere with builder.Host.UseDefaultServiceProvider(o => { o.ValidateOnBuild = true; o.ValidateScopes = true; }). The start-up cost is a one-off graph walk, typically small, and it buys you a fast failure in every environment.

  3. When: Candidate says the built-in container can't decorate open generics Why: Checks whether they can work around a container limit by closing types themselves
    How to answer

    Microsoft.Extensions.DependencyInjection (still in .NET 10) can't attach a factory or decorator to an open generic, so you close it yourself. Enumerate the entity types you use (from the DbContext model or a marker interface), and for each T register the inner EfRepository<T> as its concrete type, then register IRepository<T> with a factory that builds CachingRepository<T> around it. Do the reflection (MakeGenericType, ActivatorUtilities.CreateFactory) once at start-up and cache the resulting ObjectFactory, so each resolution is a delegate call rather than reflection. The costs: start-up work proportional to the number of entity types, factory registrations that ValidateOnBuild can't inspect, and code that isn't trimming/AOT-safe. For a handful of entities, explicit closed registrations are clearer; for many, Scrutor's Decorate(typeof(IRepository<>), typeof(CachingRepository<>)) is usually the better choice.

🛠 Real-world problems: how you handle them

Open generic fallback validator silently replaced a renamed validator
Situation
A [claims-processing] API on .NET [10] with about [140] request types used `IValidator<>` → `NoRulesValidator<>` as a fallback and assembly scanning for the real validators. A refactor renamed `LodgeClaimValidator` and moved it to a namespace the scan filter excluded.
Signals
No errors at start-up or in logs. A week later the operations team reported [37] claims with negative excess amounts. Application Insights showed `LodgeClaim` requests returning 200 with no validation failures, while the validation-failure metric for that endpoint had dropped to zero after the release.
Investigation
Compared the validation-failure custom metric per endpoint before and after the release. Resolved `IValidator<LodgeClaimRequest>` in a debugger session and saw `NoRulesValidator<LodgeClaimRequest>`. Diffed the scan filter and found the namespace change. Checked `ValidateOnBuild`: it was on, but it skips open generic descriptors, so the fallback hid the gap.
Resolution
Hotfix: registered the validator explicitly and redeployed within [2] hours; ran a data-fix script for the affected claims. Long term: removed the scan's namespace filter in favour of a marker interface, and changed the fallback so production logs a warning metric whenever `NoRulesValidator<T>` is resolved for a type in the requests assembly.
Prevention
An xUnit composition-root test that enumerates every `*Request` type and asserts its resolved validator is not `NoRulesValidator<T>`. A dashboard tile on validation failures per endpoint with an alert on a drop to zero. A PR checklist item for moving or renaming validators.

How to tell it (STAR)

**S:** In [our claims API], we used an open generic fallback validator so request types without rules still worked, and scanned an assembly for the real validators. **T:** After a refactor, [37] invalid claims got through, and I was asked to find out why and make sure it couldn't recur. **A:** I noticed the validation-failure metric for that endpoint had dropped to zero after the release, resolved the validator in a debugger and saw the fallback instead of the real one. The renamed class had fallen outside the scan's namespace filter, and `ValidateOnBuild` doesn't check open generics. I shipped an explicit registration as a hotfix, replaced the namespace filter with a marker interface, and wrote a test that resolves a validator for every request type and fails if it gets the fallback. **R:** The fix was live in [2] hours, the test caught [2] more missing validators the same week, and we haven't had a silent validation gap since.

More in Advanced DI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me