Register all viewmodel and services in ViewModelLocator

痴心易碎 提交于 2019-12-25 02:29:21

问题


I am developing a new MVVM light Wpf application.I have 25 View and ViewModels and 25 DataService Interface and its implementations (One implementation for Design time Data service and one for realtime dataservice).

For Eg, Here is a my DataService Interface for my SupplierViewModel:

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

and Here is its implementation for design time :

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)
    {
      ....
    }
}

In ViewModelLocator is I need to register all my 25 ViewModels and its 25 DataService and its implementations like this :

 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>();
        ....
    }

My question is do I need to register all my 25 ViewModels and its 25 DataService in my ViewModelLocator ?


回答1:


Another possibility would be to write a factory class ViewModelResolver this can then be injected by SimpleIoc (given you have an IViewModelResolver).

The main purpuse is to deliver a ViewModel. You can do it based on conventions, by string, by type, whatever fits best for you.

So for example ViewModelResolver.GetViewModelFor("Namespace.CustomerView");

This could be done per convention and reflection for example to return a new Instance of CustomViewModel... With this you do also have control whether you like to retrieve a cached view model (always the same) or generate a new on each request...

This is just example to get you the idea... The implementation depends on your requirements...

HTM



来源:https://stackoverflow.com/questions/23651408/register-all-viewmodel-and-services-in-viewmodellocator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!