2011-04-15 191 views
3

我使用在溫莎城堡類型化的工廠設備被添加到一個類型化的工廠設備工廠方法在溫莎城堡。我想在工廠方法生成它應該創建的實例的實例時獲得回調,以便爲實例更改屬性更改通知。通過這種方式,我不需要確保在調用工廠方法後調用「創建後」步驟,而是將此職責交給工廠。如何攔截

有沒有一種方法,無論是使用類型化的工廠設備或其他一些城堡功能上註冊生成的工廠回調或建立在其上用於執行回調工廠的攔截?

+0

將在工廠不正常攔截呢? – 2011-04-15 22:10:36

回答

0

你或許可以通過創建從AbstractFacility推導設施解決這個問題。註冊到Kernel.ComponentCreated事件並檢查創建的組件是否需要屬性更改通知。如果這樣註冊。

可以使用ComponentDestroyed事件,以確保你也很好註銷。下面的代碼片段我用它來自動註冊視圖模型與Caliburn.Micro的事件聚合

class EventRegistrationFacility : AbstractFacility 
{ 
    private IEventAggregator _eventAggregator; 

    protected override void Init() 
    { 
     Kernel.ComponentCreated += ComponentCreated; 
     Kernel.ComponentDestroyed += ComponentDestroyed; 
    } 

    void ComponentCreated(Castle.Core.ComponentModel model, object instance) 
    { 
     if (!(instance is IHandle)) return; 
     if (_eventAggregator == null) _eventAggregator = Kernel.Resolve<IEventAggregator>(); 
     _eventAggregator.Subscribe(instance); 
    } 

    void ComponentDestroyed(Castle.Core.ComponentModel model, object instance) 
    { 
     if (!(instance is IHandle)) return; 
     if (_eventAggregator == null) return; 
     _eventAggregator.Unsubscribe(instance); 
    } 

} 

親切的問候, Marwijn。