2012-10-23 117 views
0

我想使用Reflection來訂閱EventAggregator事件,因爲我試圖在運行時動態連接Prism模塊之間的事件訂閱。 (我使用的是Silverlight 5,Prism和MEF)。使用Reflection訂閱Prism EventAggregator事件

我想實現的是在我的一個模塊中調用_eventAggregator.GetEvent<MyType>().Subscribe(MyAction),但我堅持要求_eventAggregator.GetEvent<MyType>()。如何從那裏撥打電話Subscribe(MyAction)

說我的活動等級是public class TestEvent : CompositePresentationEvent<string> { }。我在編譯時不知道這一點,但我知道運行時的Type。

這是我到目前爲止有:

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>(); 

我真的很感激,在正確的方向指針。

var myEvent = generic.Invoke(eventAggregator, null) as CompositePresentationEvent<string>; 
if (myEvent != null) 
    myEvent.Subscribe(MyAction); 

假設你知道載荷類型:

回答

2

你可以做到這一點,而無需擔心你使用動態調用的事件的「類型」。

Type eventType = assembly.GetType(typeName); 
MethodInfo method = typeof(IEventAggregator).GetMethod("GetEvent"); 
MethodInfo generic = method.MakeGenericMethod(eventType); 
dynamic subscribeEvent = generic.Invoke(this.eventAggregator, null); 

if(subscribeEvent != null) 
{ 
    subscribeEvent.Subscribe(new Action<object>(GenericEventHandler)); 
} 

//.... Somewhere else in the class 

private void GenericEventHandler(object t) 
{ 
} 

現在你真的不需要知道「事件類型」是什麼。

1

可能,因爲它是那麼簡單。

就我個人而言,我看到在模塊的外部消耗的聚合事件作爲該模塊的API,我試圖將它們放置在其他模塊可以編譯的某種共享程序集中。

+0

是的,謝謝!我錯過了'作爲CompositePresentationEvent '部分。 – Phasma

0

我發現的情況下的答案是,載荷類型是這裏未知:

http://compositewpf.codeplex.com/workitem/6244

  1. 添加EventAggregator.GetEvent(類型EVENTTYPE)沒有泛型參數

  2. 得到事件
  3. 使用反射建立表達類型的動作

  4. 訂閱使用反射的事件(即調用Subscribe方法)並傳遞Expression.Compile作爲參數。

如果KeepAlive爲true,這將起作用。