Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.Repository1[T]' for service type 'Test.Domain.IRepository1[T]'.

like image 311
Palmi Avatar asked Sep 04 '16 18:09

Palmi


People also ask

How do I register a generic repository in .NET Core?

You have to register the dependencies in IServiceCollection in startup class. ASP.NET Core supports the constructor Injections to resolve the injected dependencies. Here, register the interface and their implementation into DI, using the add method of different lifetimes.

What is dependency injection in NET Core with example?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.

How do we implement dependency injection?

Dependency Injection is done by supplying the DEPENDENCY through the class's constructor when creating the instance of that class. The injected component can be used anywhere within the class. Recommended to use when the injected dependency, you are using across the class methods.


1 Answers

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.

like image 148
dotnetom Avatar answered Sep 29 '22 20:09

dotnetom