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).
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.
"An open generic registration is a descriptor where both types are generic type definitions, like
typeof(IRepository<>)andtypeof(EfRepository<>). The container doesn't do anything with it at registration time. When something asks forIRepository<Order>, theCallSiteFactoryfirst looks for an exact registration of the closed type. If there isn't one, it walks the open generic descriptors, callsMakeGenericTypewithOrder, builds a call site forEfRepository<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>→AuditLogRepositorywins 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 fitOrder. Lifetimes apply per closed type: a singletonICache<>gives you oneCache<Order>and a separateCache<Customer>.The mistake I see is assuming the container validates all of this at start-up.
ValidateOnBuildskips open generic descriptors because it has no type argument to try, so a missing dependency ofEfRepository<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."
| 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 |
| 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 |
| 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 |
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.
Checks whether the candidate understands how the built-in container resolves open generics rather than just knowing the typeof(IX<>) syntax.
Green flags
MakeGenericType at first resolution and caching per closed typeIEnumerable<T> mixes bothValidateOnBuildRed flags
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
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.
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.
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.
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.
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.
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.
IRepository<> → EfRepository<> and a closed IRepository<AuditLog> before it. Resolve both closed types and print the implementation names to confirm closed-over-open precedence.IEnumerable<IValidator<Order>>; check which ones appear.ValidateOnBuild, give EfRepository<T> an unregistered constructor dependency, and observe that Build() succeeds and the first resolution fails.DbContext model's entity types and resolves IRepository<T> for each.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));
}
}
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.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.Cache<Order> and Cache<Customer> never share state. Instead: if you need one shared object, register a non-generic singleton and inject it.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.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.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.
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.
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:
sp => ...): the body is opaque code that only runs on resolution;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.
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.
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.
Last updated 23 Nov 2026.