Palmi Palmi - 3 months ago 21
C# Question

How to inject dependencies of generics in ASP.NET Core

I have following repository classes:

public class TestRepository : Repository<Test>
{
private TestContext _context;

public TestRepository(TestContext context) : base(context)
{
_context = context;
}
}

public abstract class Repository<T> : IRepository<T> where T : Entity
{
private TestContext _context;

public Repository(TestContext context)
{
_context = context;
}
...
}

public interface IRepository<T>
{
...
}


How do I implement the dependency injection in ASP.NET Core in my
Startup.cs
?

I implemented it like this:

services.AddScoped(typeof(IRepository<>), typeof(Repository<>));


But then I get following error:


Cannot instantiate implementation type 'Test.Domain.Repository
1[T]'
for service type 'Test.Domain.IRepository
1[T]'.

Answer

Repository<T> is an abstract class, so you cannot register it as an implementation, because abstract class simply cannot be instantiated. Your registration would work fine if Repository<T> was not abstract.

If you cannot make repository class non-abstract, you can register specific implementation of your repository class:

services.AddScoped(typeof(IRepository<Test>), typeof(TestRepository));

This will correctly inject dependencies to your controller.