dimanche 17 mai 2015

Invalid argument when calling method via reflection

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!





Aucun commentaire:

Enregistrer un commentaire