As part of a unit test I'm trying to create an instance of an object that takes in a ILogger<T>
as a parameter but I don't know the T type at compile time. Instead, I have a variable that contains the type of T.
The object I'm trying to create has a constructor that looks like this:
public class PersonRepository
{
private readonly ILogger<PersonRepository> logger;
public PersonRepository(ILogger<PersonRepository> logger)
{
this.logger = logger;
}
}
How can I create an instance of ILogger<T>
from a Type
please?
I've tried doing this as the most obvious solution but it creates an ILogger
rather than an ILogger<PersonRepository>
.
var t = typeof(PersonRepository);
var loggerFactory = new LoggerFactory();
var logger = loggerFactory.CreateLogger(t);
var personRepository = Activator.CreateInstance(t, logger); // This line fails as logger is an ILogger instead of an ILogger<PersonRepository>
I've also got access to Moq to create instances if that helps provide more options here.