vendredi 7 août 2020

C# Call generic method with type as string with lambda argument

Lets say I have:

public class ConcreteJob
{
    public void ExecuteConcreteJob(string someParam) { }
}

I am used to execute it on Hangfire scheduler:

var client = new BackgroundJobClient();
client.Enqueue<ConcreteJob>(job => job.ExecuteConcreteJob("test_string_param"));

Now I would like to replace concrete type ConcreteJob with its string representation "ConcreteJob". Use reflection and do something like this (very simple said):

client.Enqueue<"ConcreteJob">(job => job.ExecuteConcreteJob("test_string_param"));

I am getting lost in all the reflection...

Lambda as parameter makes this different from other threads on stack overflow.

What I have so far:

var jobType = Type.GetType("ConcreteJob");
MethodInfo methodInfo = typeof(BackgroundJobClient).GetMethod("Enqueue").MakeGenericMethod(jobType);
var funcDelegateType = typeof(Func<>).MakeGenericType(jobType);
dynamic lambda = Expression.Lambda(funcDelegateType,
        Expression.Call(
            Expression.Parameter(jobType, "job"),
            jobType.GetMethod("ExecuteCleanup"),
            Expression.Constant(UserPrincipalName))
    );
methodInfo.Invoke(client, new[] { (Action)(lambda) });




Aucun commentaire:

Enregistrer un commentaire