C# – Inject generic interface in .NET Core

.net-core, asp.net-core, asp.net-core-mvc, c++, dependency-injection

I want to inject this interface to my controllers:

public interface IDatabaseService<T>    where T : class{    T GetItem(int id);    IEnumerable<T> GetList();    void Edit(T data);    void Add(T data);    void Remove(T data);}

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>{    public ProjectService(DbContext context)    {        this.context = context;    }    private readonly DbContext context;    public Project GetItem(int id)    {    }    public IEnumerable<Project> GetList()    {    }    public void Edit(Project data)    {    }    public void Add(Project data)    {    }    public void Remove(Project data)    {    }}

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


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?

Best Solution

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