lundi 20 novembre 2023

How to register generic services with an interface using reflection

I have multiple services with this pattern, each repository class is using generics for the context and is implementing an interface also with generics:

public partial interface IUserRepository<TContext> : IRepository<TContext, UserRow> where TContext : DbContext
{
}

public partial class UserRepository<TContext> : RepositoryBase<TContext, UserRow>, IUserRepository<TContext> where TContext : DbContext
{
}

I could register my services manually but it's not scaleable as I will have dozens of them:

services.AddScoped<IUserRepository<DatabaseApiDbContext>, UserRepository<DatabaseApiDbContext>>();
services.AddScoped<IUserRepository<DatabaseApiDbContextSandbox>, UserRepository<DatabaseApiDbContextSandbox>>();

I think I could simplify the registration? I am not sure that would work, but something like this:

services.AddScoped(typeof(IUserRepository<>), typeof(UserRepository<>));

But that would still require a line of code for each repository.

Question

I would like to use reflection for registering my repositories. For example:

  1. Get all classes in my assembly that are inheriting the generics RepositoryBase class (e.g. XYZRepository<>)
  2. For each of these classes
  • Get the type for its corresponding Repository interface (e.g. IXYZRepository<>)
  • Register the XYZRepository<> class using the corresponding IXYZRepository<> interface

But I am not good enough with reflection to achieve that. Thanks for helping out!





Aucun commentaire:

Enregistrer un commentaire