mardi 2 novembre 2021

Use reflection to forcefully cast object into interface it sort of implements

I have the following setup:

public interface IRepository<T>
{
    void Save(T entity);
}

public interface IEmailRepository : IRepository<Email> {} // completely empty!

public class MockRepository<T> : IRepository<T> {}

What I wish to do is the following:

void SomeBusinessMethod(IEmailRepository repo) { ... }

MockRepository<Email> mockRepository = CreateMockRepository<Email>();
IEmailRepository mockedEmailRepository = (IEmailRepository) mockRepository; // Invalid cast!
BusinessMethod(mockedEmailRepository);

I am aware that this isn't possible because MockRepository<T> does not inherit from IEmailRepository, even through the class and interface have the exact same signatures.

This is done in a production project and my goal is to inject a mock repository into business classes. I would prefer the possibility of using reflection to forcefully do this conversion anyways to not update the business logic code.

I found that you can use TypeBuilder and ModuleBuilder to create new types and methods with IL, but I just want to assign an interface to an instance that already sort of implements it. Is there a way to achieve this?

There are several other questions slightly related to this problem, but none have been answered with a solution that allows this setup.





Aucun commentaire:

Enregistrer un commentaire