我正在尝试使用反射调用 Prism EventAggregator,因为事件有效负载是在运行时确定的。
以下是使用 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;
}
我正在这样做:
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);
}
在我看来很好。但是当我执行最后一行“(pubSubEvent.Publish(@event);”时,我得到了异常,即使用无效参数调用发布方法。知道为什么@event参数无效吗?
问候!