Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject generic interface in .NET Core

I want to inject this interface to my controllers:

public interface IDatabaseService<T>
{
    IEnumerable<T> GetList();
    ...
}

I want to use generic, because in my WebApi project i have controllers like ProjectController, TaskController etc and i want to use generic interface to each of type (for example, IDatabaseService<Project>, IdatabaseService<Task> etc).

Class, that will be injected to controller will look like this:

public class ProjectService : IDatabaseService<Project>
{
    private readonly DbContext context;

    public ProjectService(DbContext context)
    {
        this.context = context;
    }

    public IEnumerable<Project> GetList() { }
    ...
}

But when I try to ineject in my Startup.cs:

services.AddScoped<IDatabaseService<T>>();

I need to pass T type.

My question is, how to make injection generic and how inject it properly in controller? For example:

public class ProjectController : ControllerBase
{
    private readonly ProjectService projectService;

    public ProjectController (IDatabaseService<Project> projectService)
    {
        this.projectService = projectService;
    }
}

If it will work? And is it good practice to make generic interface to inject into controllers? If no, how to do it better?

like image 283
michasaucer Avatar asked May 15 '19 07:05

michasaucer


People also ask

Can we use generic on interface in C#?

You can declare variant generic interfaces by using the in and out keywords for generic type parameters. ref , in , and out parameters in C# cannot be variant. Value types also do not support variance. You can declare a generic type parameter covariant by using the out keyword.

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.

Can you create an instance of generic interface?

In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap<String, List<String>>(); is valid.

What is generic in .NET core?

First introduced in . NET Framework 2.0, generics are essentially a "code template" that allows developers to define type-safe data structures without committing to an actual data type.


1 Answers

You can do this by adding the below line in Startup.cs

// best practice  
services.AddTransient(typeof(IDatabaseService<>),typeof(DatabaseService<>));

Visit Here to know more about Dependency injection in ASP.NET Core

like image 123
Voodoo Avatar answered Sep 19 '22 17:09

Voodoo