lundi 13 mars 2023

Invoke generic extension method via reflection results in error is not a GenericMethodDefinition

I have the below extension method which I am trying to invoke with various instantiated classes in an array. As extension methods cannot be invoked with dynamic I have tried using the array type as object or IMessage. However, as this calls MassTransit and Azure Service Bus, they need the exact type for it to work, even though it will compile. I have thought that perhaps reflection would work however the below results in System.InvalidOperationException: System.Threading.Tasks.Task``1[Helix.Sdk.Contracts.CommandResponse] ExecuteCommand[Object](MassTransit.IBus, System.Object, System.Threading.CancellationToken) is not a GenericMethodDefinition. MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true.

Is there anyway for this to work so it knows the correct type at runtime?

foreach (var command in commands)
{
   //Bus.ExecuteCommand(command); //won't work with dynamic or object at runtime

   var func = new Func<IBus,object, CancellationToken, Task<CommandResponse>>(BusCommandExtensions.ExecuteCommand);
   func.Method.MakeGenericMethod(command.GetType());
   await func.Invoke(Bus,command, CancellationToken.None);
}

public static class BusCommandExtensions {

    //Removed other methods for brevity     

    public static async Task<CommandResponse> ExecuteCommand<T>(this IBus bus, T command, CancellationToken cancellationToken = default) where T : class =>
        await ExecuteCommand(
            bus, command, _ => { },
            cancellationToken
        );

}




Aucun commentaire:

Enregistrer un commentaire