-1

In order to create a simple event bus to implement a communication infrastructure for microservice I hit this question:

How can I invoke multiple Action with different generic types?

  • There is possibly some interesting question here... But currently post does not provide any details to clarify why it is any different than standard duplicate. Clarifying that would actually solve two problems with this post - not showing any research/being unclear as well explaining why it should not be closed as duplicate. Note that providing an answer is not enough because that alone does not make question clear. – Alexei Levenkov May 01 '20 at 01:24
  • The duplicate you mention doesn´t handle the Action. It took me some reflection acrobatic to understand that a "Invoke" method is inside the Action. May this can save some time to others. – Marco Alber May 01 '20 at 13:07

1 Answers1

0

My solution for this issue:

void Main()
{
    var data = new object[] { new ProviderA(), new ProviderB() };

    var events = new List<object> {
        new Action<ProviderA>(provider => provider.Fire()),
        new Action<ProviderB>(provider => provider.Fire())
    };

    Invoke(events[0], data);
    Invoke(events[1], data);
}

void Invoke(object action, object[] data)
{
    var genericActionType = action.GetType().GenericTypeArguments[0];
    var dataObject = data.First(f => f.GetType() == genericActionType);

    var genericAction = typeof(Action<>).MakeGenericType(dataObject.GetType());
    genericAction.GetMethod("Invoke").Invoke(action, new object[]{ dataObject });
}

public class ProviderA
{
    public void Fire() { Console.WriteLine("Provider A fired"); }
}

public class ProviderB
{
    public void Fire() { Console.WriteLine("Provider B fired"); }
}