I have a generic interface which has many implementations. I expect to have more implementations of this generic interface in the future. However, I don’t want to manually register these implementations in the service container every time I add a new one. It’d also cause runtime exception if I forget to register one of these implementations. In this post, I’m going to show how to automatically register all implementations of a generic interface during start up.
Let’s say the generic interface looks similar to the one below
public interface IGenericInterface
{
bool DoSomething(string someInput);
}
And it has 2 implementations as followed
public class ClassA : IGenericInterface<ClassA>
{
public bool DoSomething(string someInput)
{
// Business logic goes here
return true;
}
}
public class ClassB : IGenericInterface<ClassB>
{
public bool DoSomething(string someInput)
{
// Business logic goes here
return false;
}
}
Then, in order to automatically register these implementations, in ConfigureServices method in Startup.cs class, do the following
public void ConfigureServices(IServiceCollection services)
{
// Other service registrations go here
var assemblyTypes = Assembly.GetAssembly(typeof(Startup)).GetTypes();
foreach (var genericType in assemblyTypes.Where(x => !x.IsInterface &&
x.GetInterfaces().Any(i => i.IsGenericType &&
typeof(IGenericInterface<>).IsAssignableFrom(i.GetGenericTypeDefinition()))))
{
services.AddTransient(genericType.GetInterfaces().First(), genericType);
}
}