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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With