I want to subscribe to an EventAggregator event using Reflection, because I am trying to dynamically wire up event subscriptions between Prism modules at runtime. (I’m using Silverlight 5, Prism and MEF).
What I want to achieve is calling _eventAggregator.GetEvent<MyType>().Subscribe(MyAction) in one of my modules, but I am stuck at calling _eventAggregator.GetEvent<MyType>(). How can I proceed from there to call Subscribe(MyAction)?
Say my Event class is public class TestEvent : CompositePresentationEvent<string> { }. I don’t know this at compile time, but I know the Type at runtime.
Here is what I have got so far:
Type myType = assembly.GetType(typeName); //get the type from string
MethodInfo method = typeof(IEventAggregator).GetMethod("GetEvent");
MethodInfo generic = method.MakeGenericMethod(myType);//get the EventAggregator.GetEvent<myType>() method
generic.Invoke(_eventAggregator, null);//invoke _eventAggregator.GetEvent<myType>();
I would really appreciate a pointer in the right direction.
You can do this without having to worry about the “type” of event you are invoking by using dynamics.
Now you really never need to know what the “event type” is.