문제

I would like to use

eventAggregator.GetEvent(typeof(SomeDomainEvent)).Subscribe();

instead of

eventAggregator.GetEvent<SomeDomainEvent>().Subscribe();

But GetEvent is not overloaded for that. How can I solve it?

Thank you.

도움이 되었습니까?

해결책

You will need to use reflection.

// Equivalent to:
//
// SomeDomainEvent eventObject = eventAggregator.GetEvent<SomeDomainEvent>();
MethodInfo getEventMethod = typeof(IEventAggregator).GetMethod("GetEvent");
MethodInfo genericGetEventMethod = getEventMethod.MakeGenericMethod(typeof(SomeDomainEvent));
object eventObject = genericGetEventMethod.Invoke(eventAggregator, null);

// Now choose the version of "Subscribe" you want to call
// Equivalent to:
// 
// eventObject.Subscribe(MyEventHandler);
Type[] subscribeTypes = new Type[] { typeof(Action<SomeDomainEventArgs>) });
MethodInfo subscribeMethod = eventObject.GetType().GetMethod("Subscribe", subscribeTypes);
subscribeMethod.Invoke(eventObject, new object[] { new Action<SomeDomainEventArgs>(MyEventHandler) });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top