2013-03-20 118 views
0

目前,我有我的視圖模型MVVM,MEF,Silverlight和服務代理

public CartViewModel() : this(new PayPalCompleted()) { } 

    public CartViewModel(IPayPalCompleted serviceAgent) 
    { 
     if (!IsDesignTime) 
     { 
      _ServiceAgent = serviceAgent; 
      WireCommands(); 
     } 
    } 

下面的構造,我想我的modularise應用棱鏡與MEF。我的模塊工作正常,但我遇到了我的一個視圖模型的問題。

我的問題是,我需要在構造函數中導入EventAggregator,但我有我是如何做到這一點有paramaterless構造,以及作爲一個進口構造

[ImportingConstructor] 
    public CartViewModel([Import] IEventAggregator eventAggregator) 
    { 
     if (!IsDesignTime) 
     { 
      _ServiceAgent = new PayPalCompleted(); 
      TheEventAggregator = eventAggregator; 
      WireCommands(); 

     } 
    } 

即我想要做的問題像這樣的東西

 public CartViewModel() : this(new PayPalCompleted(), IEventAggregator eventAggregator) { } 

    [ImportingConstructor] 
    public CartViewModel(IPayPalCompleted serviceAgent, IEventAggregator eventAggregator) 
    { 
      ...stuff 
    } 

這是不正確的我知道...什麼是?

問題的一部分,我認爲是,當使用導入構造函數時,默認情況下構造函數中的參數是導入參數 - 這意味着它們需要MEF的相應導出才能正確編寫。這可能意味着我應該導出我的paypay服務?還是應該?

感謝

回答

0

處理這個最簡單的方法是揭露類型IEventAggregator的屬性,實現IPartImportsSatisifiedNotification和該方法處理事件訂閱。

像這樣的事情

public class CartViewModel : IPartImportsSatisfiedNotification 
{ 
    private readonly IPayPalCompleted _serviceAgent; 

    public CartViewModel(IPayPalCompleted serviceAgent) 
    { 
     this._serviceAgent = serviceAgent; 
     CompositionInitializer.SatisfyImports(this); 
    } 

    [Import] 
    public IEventAggregator EventAggregator { get; set; } 

    void IPartImportsSatisfiedNotification.OnImportsSatisifed() 
    { 
     if (EventAggregator != null) 
     { 
      // Subscribe to events etc. 
     } 
    } 
} 
+0

我已經做了類似的事情,但忘了添加CompositionInitializer.SatisfyImports(本); !謝謝 – 72GM 2013-03-25 12:05:41