Registering Open Generics in ASPNET Core Dependency Injection

Date Published: 30 April 2017

Registering Open Generics in ASPNET Core Dependency Injection

If you have a generic interface and implementation that you want to configure for dependency injection in ASP.NET Core startup, there is a simple way to do so. If you only use the generic methods for adding services, such as:

services.AddScoped<IImageService,ImageService>();

then you will not find a way to do it. You canโ€™t do this:

// does not work
services.AddScoped<IGenericRepository<T>,EFRepository<T>>();

Instead, you need to use the non-generic overload of the Add[Lifetime] method, and use the typeof keyword to specify your open generic interface and implementation. Hereโ€™s an example:

// this works
services.AddScoped(typeof(IGenericRepository<>), typeof(EFGenericRepository<>));

Steve Smith

About Ardalis

Software Engineer

Steve is an experienced software architect and trainer, focusing currently on ASP.NET Core and Domain-Driven Design.


Ardalis

Copyright ยฉ 2020