Inject generic interface in .NET Core
1.) if you want to write hard code
services.AddScoped<IDatabaseService<Project>, ProjectService>();
2.) if you want to register dynamically that all types of implemented IDatabaseService<>
System.Reflection.Assembly.GetExecutingAssembly()
.GetTypes()
.Where(item => item.GetInterfaces()
.Where(i => i.IsGenericType).Any(i => i.GetGenericTypeDefinition() == typeof(IDatabaseService<>)) && !item.IsAbstract && !item.IsInterface)
.ToList()
.ForEach(assignedTypes =>
{
var serviceType = assignedTypes.GetInterfaces().First(i => i.GetGenericTypeDefinition() == typeof(IDatabaseService<>));
services.AddScoped(serviceType, assignedTypes);
});
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