I need to instantiate a type that MUST have a IConfiguration
parameter, but MAY have other parameters.
Currently I use the following code:
Activator.CreateInstance(myType, BindingFlags.CreateInstance, null, new object[] { configuration }, CultureInfo.InvariantCulture);
myType
is the type to instantiate. Written like this, it requires a constructor that has exactly one parameter of type IConfiguration
. As you can see, I pass the configuration
object via object array to satisfy this requirement.
Now there is a new requirement: The constructor of myType
can have multiple parameters. One of them has to accept an IConfiguration
object. The other parameters can be ignored (or set to default) in this part of the code. How can I achieve this?
Edit:
These are possible types for myType
. V1 is the current requirement, V2 is the new requirement. All three variants are valid and need to be instantiated with a configuration
object.
public class PluginV1
{
private readonly IConfiguration configuration;
public PluginV1(IConfiguration configuration)
{
this.configuration = configuration;
}
}
public class PluginV2_A
{
private readonly IConfiguration configuration;
private readonly IExampleService exampleService;
public PluginV2_A(IConfiguration configuration, IExampleService exampleService)
{
this.configuration = configuration;
this.exampleService = exampleService;
}
}
public class PluginV2_B
{
private readonly IConfiguration configuration;
private readonly IEnvironment environment;
public PluginV2_B(IConfiguration configuration, IEnvironment environment)
{
this.configuration = configuration;
this.environment = environment;
}
}