我正在开发一个新的MVVM light Wpf应用程序。我有25个View和ViewModels以及25个DataService接口及其实现(一个用于设计时数据服务,一个用于实时数据服务)。
对于Eg,这是我的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个ViewModel及其25个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吗?
答案 0 :(得分:3)
另一种可能性是编写工厂类ViewModelResolver
然后可以SimpleIoc
注入(假设您有IViewModelResolver
)。
主要的用途是提供ViewModel。您可以根据约定,字符串,类型,最适合您的方式来执行此操作。
例如ViewModelResolver.GetViewModelFor("Namespace.CustomerView");
这可以按照约定和反射来完成,例如返回CustomViewModel
的新实例...
有了这个,您还可以控制是否要检索缓存的视图模型(始终相同)或在每个请求上生成新的...
这只是让你了解的例子......实施取决于你的要求......
HTM