0
votes

I am trying to call the Prism EventAggregator using reflection, because the event payload is determined at runtime.

Here is the normal way to use the EventAggregator:

        [TestMethod]
    public void WhenEventIsPublishedTheSubscriberReceivesIt()
    {
        var eventAggregator = new EventAggregator();

        eventAggregator.GetEvent<PubSubEvent<string>>().Subscribe(Subscription);
        eventAggregator.GetEvent<PubSubEvent<string>>().Publish(Constants.TestSymbol);

        Assert.IsTrue(this.subscriptionReceived);
    }

    private void Subscription(string data)
    {
        this.subscriptionReceived = true;
    }

I am doing this:

            var commandHandlerLocator = this.container.Resolve<ICommandHandlerLocator>();

        var t = command.GetType();

        dynamic commandHandler = commandHandlerLocator.GetType()
            .GetMethod("GetCommandHandler")
                .MakeGenericMethod(command.GetType()).Invoke(commandHandlerLocator, null);

        IEnumerable<IEvent> events = commandHandler.Execute(command);

        foreach (var @event in events)
        {
            var typedEvent = typeof(PubSubEvent<>).MakeGenericType(@event.GetType());

            dynamic pubSubEvent = this.eventAggregator.GetType()
                .GetMethod("GetEvent")
                    .MakeGenericMethod(typedEvent).Invoke(this.eventAggregator, null);

            pubSubEvent.Publish(@event);
        }

Here you see the the method and method argument variables

Looks fine to me. But when I execute the last line "(pubSubEvent.Publish(@event);" I get the exception, that the Publish-method is called with invalid arguments. Any idea why the @event argument is invalid?

Regards!

1

1 Answers

0
votes

Found the answer. I needed to strongly type the @event:

        private void Publish<T>(T @event) where T : IEvent
    {
        var eventAggregator = new EventAggregator();
        var pubSubEventType = typeof(PubSubEvent<>).MakeGenericType(typeof(T));

        dynamic pubSubEvent = eventAggregator.GetType()
                    .GetMethod("GetEvent")
                        .MakeGenericMethod(pubSubEventType).Invoke(eventAggregator, null);

        pubSubEvent.Publish(@event);
    }