2014-05-14 55 views
0

我正在開發一個新的MVVM輕型Wpf應用程序。我有25個View和ViewModels以及25個DataService接口及其實現(一個用於設計時數據服務,一個用於實時數據服務)。在ViewModelLocator中註冊所有視圖模型和服務

對於例如,下面是我的DataService接口爲我SupplierViewModel:

interface ISupplierDataService 
{ 
    ObservableCollection<Tbl_Supplier> GetAllSuppliers(); 
    int GetSupplierCount(string supplierNameMatch); 
} 

,這裏是它的設計時間實現:

class SupplierDataServiceMock : ISupplierDataService 
{ 

    public ObservableCollection<Tbl_Supplier> GetAllSuppliers() 
    { 
     ..... 
    } 

    public int GetSupplierCount(string supplierNameMatch) 
    { 
     .... 
    } 
} 

class SupplierDataService : ISupplierDataService 
{ 

    public ObservableCollection<Tbl_Supplier> GetAllSuppliers() 
    { 
     .... 
    } 

    public int GetSupplierCount(string supplierNameMatch) 
    { 
     .... 
    } 
} 

在ViewModelLocator是我需要註冊我的所有25個ViewModels及其DataService及其實現如下:

static ViewModelLocator() 
    { 
     ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); 

     if (ViewModelBase.IsInDesignModeStatic) 
     { 
      SimpleIoc.Default.Register<ISupplierDataService, SupplierDataServiceMock>(); 
      SimpleIoc.Default.Register<ICustomerDataService, CustomerDataServiceMock>(); 
      .... 
     } 
     else 
     { 
      SimpleIoc.Default.Register<ISupplierDataService, SupplierDataService>(); 
      SimpleIoc.Default.Register<ICustomerDataService, CustomerDataService>(); 
      .... 
     } 

     SimpleIoc.Default.Register<MainViewModel>(); 
     SimpleIoc.Default.Register<SupplierViewModel>(); 
     SimpleIoc.Default.Register<CustomerViewModel>(); 
     .... 
    } 

我的問題是我需要在我的ViewModelLocator中註冊所有25個ViewModel及其25個DataService嗎?

+1

有什麼問題? – Mashton

+0

@Mashton,我加了我的問題 – Angel

+0

是的,你必須在locator中添加所有的viewmodels和services。 –

回答

3

另一種可能性是編寫一個工廠類ViewModelResolver,然後可以通過SimpleIoc注入(假設你有一個IViewModelResolver)。

主要的缺點是提供一個ViewModel。你可以根據慣例,字符串,類型,適合你的最佳方式來完成。

因此,例如ViewModelResolver.GetViewModelFor("Namespace.CustomerView");

這可能按照慣例和反射來實現,例如返回的CustomViewModel ... 有了這個新的實例你還可以控制你是否要檢索緩存視圖模型(總是相同)或生成新的每個請求......

這僅僅是例子,讓你的想法...的實現依賴於你的要求......

HTM

相關問題