C
C#ā€¢2y 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)
{}
}
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);
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.'
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?
5 Replies
Anton
Antonā€¢2y ago
it doesn't call private constructors by default it needs an extra parameter
Hugh
HughOPā€¢2y ago
It should be a public constructor that's available to it, and I'm passing the logger in as a second parameter to CreateInstance()
Anton
Antonā€¢2y ago
it's literally private in the code above
Hugh
HughOPā€¢2y ago
oh, sorry - that's my mistake when typing up the code in this question let me check my actual code too Ah shit, yes - it's private in my actual code Thanks - silly mistake! šŸ¤¦ā€ā™‚ļø
Anton
Antonā€¢2y ago
np
Want results from more Discord servers?
Add your server