0

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.

Benjamin
  • 353
  • 1
  • 4
  • 17
  • Do you want to create specific class instance that implement `ILogger` or you want to create a mock for `ILogger`? – Mat J Dec 17 '21 at 05:55
  • "it creates an ILogger rather than an ILogger" I think you are right that the implicitly typed variable that holds the return value will be typed (by the compiler) as an `ILogger`. But that doesn't mean the object itself isn't an `ILogger`. Have you checked the runtime type using `GetType()`? – John Wu Dec 17 '21 at 06:08
  • In response to all comments I've added some additional code to the question that I think might help. Yes, I am specifically wanting an ILogger in this case, not an ILogger as the Activator.CreateInstance() call can't find a constructor for it because the logger is a different type than expected. I've just spent more time investigating @KlausGütter's answer and I've found a solution that works for me :) – Benjamin Dec 17 '21 at 07:02

0 Answers0