我试图使用反射来调用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);”我得到异常时,使用无效参数调用了Publish方法。任何想法为什么@event参数无效?
问候!
答案 0 :(得分:0)
找到答案。我需要强烈输入@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);
}