C#C
C#4y ago
Hugh

✅ Using Activator.CreateInstance() when the constructor has arguments - not finding constructor

I'm trying to create a class instance dynamically using Activator.CreateInstance(), and it's crashing and not finding the constructor.

My object looks like this:
public class MyClass : MyBaseClass
{
    MyClass(ILogger logger) : base(logger)
    {}
}


And I'm creating it like this:
Type myClassType = typeof(MyClass);
LoggerFactory loggerFactory = new();
ILogger logger = loggerFactory.CreateLogger(myClassType);
MyBaseClass? myInstance = (MyBaseClass?)Activator.CreateInstance(myClassType, logger);


However, when it hits the CreateInstance() line, an exception occurs:
An exception of type 'System.MissingMethodException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'Constructor on type 'MyClass' not found.'


Any idea what I'm doing wrong here?
Was this page helpful?