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?
answer
- the Type-based overload
- typeof(IRepository<>), typeof(EfRepository<>)
- closed at resolve time
- exact match beats open generic
- no factory lambdas for open generics
basics
~10 sRegister 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.
solid answer
~40 sAn **open generic** registration uses the `Type` overloads: `services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>))`. The generic overload `AddScoped<IRepository<>, EfRepository<>>()` does not compile, because C# does not allow unbound generic types as type arguments. When something asks for `IRepository<Listing>`, the container builds `EfRepository<Listing>` and caches it per lifetime like any other service. The implementation must itself be an open generic definition with the same number of type parameters, and it cannot be a factory lambda; otherwise building the provider throws `ArgumentException`. A closed registration such as `AddScoped<IRepository<Order>, OrderRepository>()` wins for `IRepository<Order>` whatever the registration order, because the container looks for an exact match before trying open generics. `IEnumerable<IRepository<Order>>` contains both.
code
csharp · 14 linesbuilder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
builder.Services.AddScoped<IRepository<Order>, OrderRepository>(); // wins for Order
public interface IRepository<T> where T : class
{
ValueTask<T?> FindAsync(Guid id, CancellationToken ct);
}
public class EfRepository<T>(MarketplaceDbContext db) : IRepository<T>
where T : class
{
public ValueTask<T?> FindAsync(Guid id, CancellationToken ct) =>
db.Set<T>().FindAsync([id], ct);
}go deeper
Recall the typeof(IRepository<>), typeof(EfRepository<>) registration and that one line serves every entity type.
Explain how the container closes the type on demand, why exact closed registrations win regardless of order, and which registrations throw at build time.
Cover constraint handling (throw for a single resolve, skip in an enumerable) and the validation gap for open generics, and how a test closes it.
Judge when a generic repository over EF Core adds value and when per-aggregate repositories or the DbContext directly serve the team better.
## Registering the repository once An **open generic type** is a generic type with no type arguments filled in, written `IRepository<>` in `typeof`. The built-in container accepts open generics as both service and implementation: ```csharp builder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>)); ``` In the artisan marketplace that one line covers `IRepository<Listing>`, `IRepository<Maker>`, `IRepository<Order>` and every entity added later. When a constructor asks for `IRepository<Listing>`, the container closes the implementation to `EfRepository<Listing>`, resolves its constructor parameters (here the scoped `DbContext`), and caches the instance according to the lifetime. Each closed type has its own instance, so within a request `IRepository<Listing>` and `IRepository<Maker>` are different objects. You must use the `Type`-based overloads. `AddScoped<IRepository<>, EfRepository<>>()` is a compile error, because C# does not accept an unbound generic type as a type argument. ## Rules the container enforces These checks run when the service provider is built, at `builder.Build()`, and throw `ArgumentException`: - The implementation must be an **open generic definition**. A factory registration such as `AddScoped(typeof(IRepository<>), sp => ...)` compiles but fails with "Open generic service type '...' requires registering an open generic implementation type." The container has no way to hand the requested `T` to a lambda. - The **arity** must match. `IRepository<T>` cannot map to `EfRepository<TEntity, TKey>`. - The implementation must be concrete, not abstract or an interface. ## Closed beats open You can add a hand-written repository for one entity next to the generic one: ```csharp builder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>)); builder.Services.AddScoped<IRepository<Order>, OrderRepository>(); ``` | Request | Result | |---|---| | `IRepository<Listing>` | `EfRepository<Listing>` from the open registration | | `IRepository<Order>` | `OrderRepository`, the exact match | | `IEnumerable<IRepository<Order>>` | both, in registration order | For a single service, the container first looks for a descriptor registered for the **exact closed type** and only then for an open generic definition. The closed registration therefore wins even if it was registered **before** the open one. This is a difference from plain last-wins, which applies among descriptors of the same service type. The enumerable form collects exact and open matches together, ordered as they were registered. ## Generic constraints If the implementation declares constraints, for example `EfRepository<T> where T : class, IEntity`, the container cannot close it for a type that breaks them: 1. A **single** resolve of `IRepository<AuditNote>` (where `AuditNote` is not an `IEntity`) throws `ArgumentException`. 2. An `IEnumerable<IRepository<AuditNote>>` **skips** the registration whose constraints fail and returns the others. The second behaviour lets you register several constrained open generics, such as one `IPayoutRule<T>` implementation for physical goods and one for digital downloads, and let the enumerable pick whichever apply. ## Validation and other limits - `ValidateOnBuild`, on by default in Development, **skips open generic registrations**, because it cannot know which `T` will be requested. A missing dependency of `EfRepository<T>` surfaces on the first resolve, not at startup. A test that resolves one closed type per entity closes that gap. - Keyed registration works with open generics too: `AddKeyedScoped(typeof(IRepository<>), "archive", typeof(ArchiveRepository<>))`. - Under Native AOT, closing a generic over a value type may not be possible at run time, and the container throws instead. ## Choosing per-entity registrations instead An open generic is convenient, but it is not always the right call. A closed registration per aggregate, or no repository at all with the `DbContext` injected directly, can be clearer when: - most entities need custom queries anyway, so the generic `EfRepository<T>` is overridden for nearly every type; - the generic interface exposes operations, such as delete, that some aggregates must never allow; - you want `ValidateOnBuild` to cover the graph, which closed registrations allow and open generics do not. The open generic shines for genuinely uniform cross-cutting types: `ILogger<T>` itself is registered by the logging library as an open generic (`ILogger<>` to `Logger<>`), and the options library registers `IOptions<>` the same way. The model: one `Type`-based line covers every entity, an exact closed registration overrides it per type, and constraint failures throw for a single resolve but are skipped in an enumerable.
- Why does ValidateOnBuild not catch a missing constructor dependency of EfRepository<T>?Validation walks each registered descriptor, but an open generic descriptor has no concrete type to build until someone asks for `IRepository<Listing>`. The container skips open generic registrations during validation, so the error appears on the first resolve. A unit test that resolves one closed repository per entity type restores the startup-time check.
- How can a constrained open generic be useful in an IEnumerable<T> injection?When the container builds `IEnumerable<IPayoutRule<DigitalDownload>>`, it tries every open registration and silently skips those whose constraints `DigitalDownload` does not satisfy. Registering several constrained implementations therefore yields exactly the rules that apply to each type, without any manual filtering code.
- AddScoped<IRepository<>, EfRepository<>>() is the way to register an open generic.
- An open generic can be registered with a factory lambda that receives the requested T.
- A closed IRepository<Order> registration wins only if it is registered after the open one.
- ValidateOnBuild checks every open generic registration's dependencies at startup.
- A single resolve silently skips an open generic whose constraints the type argument breaks.