Ilya Chernomordik
Ilya Chernomordik

Reputation: 30175

How to pass a dynamically typed Action<T> to a method

I have a 3d party job execution library (hangfire) that accepts Action<T>:

Add(Action<T> action);

I can easily call something like that:

Add((MyJob job) => job.Run());

But I want to load the job dynamically via reflection, so I have a class name "MyNamespace.MyJob" that I can use. I cannot figure out how I can create required parameter with reflection.

P.S. The class implements IJob, but I cannot unfortunately use Action<IJob>, because hangfire will use that argument to resolve from the DI container later.

Upvotes: 2

Views: 789

Answers (1)

usr
usr

Reputation: 171178

It looks like Hangfire uses the type argument to ask the DI container to supply a value. That's why the delegate actually needs to have the right type. Using Action<object> would not work.

static void AddToHangfire<T>() where T : ICommand {
 Add((T job) => job.Run());
}

Now you need to use reflection to call that method. You can use MethodInfo.MakeGenericMethod and MethodInfo.Invoke to do that.

Upvotes: 3

Related Questions