Registering a closed generic class implementation with an opened generic interface

1.4k Views Asked by At

I've just realized, that you can't register a dependency injection like this:

services.AddScoped(typeof(IConcreteRepository<,>), typeof(DepartmentRepository));

DI forbids registering non-generic class with generic interface.

public interface IConcreteRepository<TEntity, TId> : IRepository<TEntity, TId> where TEntity : class
{}

public abstract class BaseEntityFrameworkRepository<TEntity, TId> : IConcreteRepository<TEntity, TId> where TEntity : class where TId: struct
{}

public class DepartmentRepository : BaseEntityFrameworkRepository<Department, int>
{}

Are there any 3rd party DI libraries that can make registering DepartmentRepository with IConcreteRepository<,> possible?

I need a solution of this problem no matter the library - if it's possible with the default .NET Core 3 framework it would be fantastic, but if there are any 3rd party libraries that can make this possible, I'm ok as well.


EDIT:

I should mention that registering like this throws the following exception:

An error occurred while accessing the Microsoft.Extensions.Hosting services. 

Error: Open generic service type 'CompanyName.ApplicationName.DAL.Repository.Contracts.IConcreteRepository`2[TEntity,TId]' requires registering an open generic implementation type. (Parameter 'descriptors').
1

There are 1 best solutions below

0
Guru Stron On BEST ANSWER

You should register your repository as closed generic interface:

services.AddScoped<IConcreteRepository<Department, int>, DepartmentRepository>();