mardi 2 août 2022

Invoking non static method from type with constructor with dependency injection parameters

I need to invoke a member function from a non-static type which has a contructor which receives parameters via dependency injection. I have to do this because I only receive the name of the object as a string via API call, I have several classes which have the same method but different names and I use the name of the object to invoke the correct method.

Normally I would call it like this:

var type = assembly.GetType($"{projectName}.{typeName}");

if (type == null)
{
    throw new ArgumentException($"{nameof(typeName)} not found");
}

var instance = new WhateverType(some arguments...)

await (Task)type.InvokeMember(methodName, BindingFlags.InvokeMethod |
    BindingFlags.Public | BindingFlags.Instance, null, null,
    args.Select(a => a.Value).ToArray(), null, instance, args.Select(a => a.Key).ToArray());

Where args is a dictionary which has a pair with parameter name and value.

The thing is, I don't think I want/can pass the instance of the object because those some arguments... are interfaces which are instantiated at startup and have themselves interface parameters, like for example:

builder.RegisterType<Service>()
    .As<IService>().InstancePerLifetimeScope();

Where builder is Autofac.ContainerBuilder.

And are used via dependency injection pattern, i.e.:

WhateverType(Iservice service)
{
    _service = service; 
} 

Where _service is a private member IService service and itself has interface parameters which themselves have interface parameters and so forth.

How could I do this? How do you instantiate a class that is normally instantiated by dependency injection at startup.





Aucun commentaire:

Enregistrer un commentaire