2010-05-21 112 views
0

我有一個視圖模型,它需要在構造函數中的兩個參數是相同類型:MVVM && IOC &&子的ViewModels

public class CustomerComparerViewModel 
{ 
    public CustomerComparerViewModel(CustomerViewModel customerViewModel1, 
            CustomerViewModel customerViewModel2) 
    { 

    } 
} 

public class CustomerViewModel 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

如果我不使用IOC我可以只新了視圖模型並傳入子視圖模型。我可以將兩個視圖模型打包到一個類中,並將其傳遞給構造函數,但是如果我有另一個只需要一個CustomerViewModel的視圖模型,我需要傳入視圖模型不需要的東西。

我該如何處理使用IOC的問題?我使用Ninject btw。

感謝

回答

1

這裏是如何做到這一點在Ninject:

Container.Bind<CustomerViewModel>().ToSelf().WhenTargetHas<CustomerA>(); 
Container.Bind<CustomerViewModel>().ToSelf().WhenTargetHas<CustomerB>(); 
在你使用的是他們在類的構造函數

然後:

public class CustomerComparerViewModel 
{ 
    public CustomerComparerViewModel([CustomerA]CustomerViewModel customerA, 
            [CustomerB]CustomerViewModel customerB) 
    { 

    } 
} 
1

我不熟悉Ninject,但它似乎對我來說,爲了讓國際奧委會知道你就必須設置這些對象事先什麼CustomerViewModels注入到你的構造。使用MEF一樣的屬性和代碼的僞它可能看起來像......

[Export()] 
public class CustomerSelectorViewModel 
{ 
    [Export("CustomerA")] 
    public class CustomerViewModel FirstSelection {get;set;} 

    [Export("CustomerB")] 
    public class CustomerViewModel SecondSelection {get;set;} 
} 

[Export()] 
public class CustomerComparerViewModel 
{ 
    [ImportingConstructor] 
    public CustomerComparerViewModel([Import("CustomerA")]CustomerViewModel customerViewModel1, [Import("CustomerB")]CustomerViewModel customerViewModel2) 
    { 

    } 
} 
相關問題