dimanche 21 février 2021

How to register multiple implementations with its own interface in ASP.NET Core using Reflection?

I'm new to the Dependency Injection in ASP.NET Core 3.1, and I'm trying to create Singleton instances of my Repository classes using Reflection, but I can't get it to work.

Currently, the BookService uses the BookRepository from the DI:

public class BookService : IService
{
    private readonly IBookRepository _bookRepository;

    public BookService(IBookRepository bookRepository)
    {
        _bookRepository = bookRepository;
    }

    public async Task<Book> GetById(string id)
    {
        var find = await _bookRepository.FindAsync(id);
        return find;
    }
}

It works because I added a singleton service to the container, with the following code (link to Microsoft Docs): services.AddSingleton<IBookRepository, BookRepository>();

I'm trying to achieve the same result using Reflection.

BookRepository

public class BookRepository : BaseRepository<Book>, IBookRepository
{
}

IBookRepository

public interface IBookRepository : IAsyncRepository<Book>
{
}

This is what I have so far:

// Get all classes implementing IAsyncRepository
var repositoryTypes = assembly.GetTypes().Where(x => !x.IsInterface && x.GetInterface(typeof(IAsyncRepository<>).Name) != null);
foreach (var repositoryType in repositoryTypes)
   // Adds a singleton service of BookRepository
   services.AddSingleton(repositoryType);

But as you can see, the code above is adding only the BookRepository, missing to reference the IBookRepository interface, so it's throwing the following error:

System.ArgumentException: 'Cannot instantiate implementation type 'IBookRepository' for service type 'IBookRepository'.'

Do you know how can I do that?





Aucun commentaire:

Enregistrer un commentaire