MVVM中的后台加载和构造函数注入/).这是我的ViewModel:publicclassPersonsViewModel:ViewModelBase{privatereadonlyIRepository_personRepository;私人IEnumerable_persons;publicIEnumerablePersons{get{return_persons;}私有集{_persons=值;OnPropertyChanged("人");IRepositorypersonRepository){if(personRepository==null)thrownewArgumentNullException("personRepository");_personRepository=personRepository;这个ViewModel是在Window中使用的,我需要在Window打开的时候加载大家。我想过很多解决方案,但我不能决定哪个是最好的(或者也许有更好的方法)。我有两个限制:-所有数据都必须在另一个线程中加载,因为加载可能需要几秒钟(数据库中有大量数据),而且我不想冻结UI。–ViewModel必须是可测试的。–=[第一种解决方案:延迟加载]=–publicclassPersonsViewModel:ViewModelBase{privateIEnumerable_persons;publicIEnumerablePersons{get{if(_persons==null)_persons=_personRepository.GetAll();返回_persons;我不喜欢这个解决方案,因为数据是在主线程中加载的。–=[第二个解决方案:加载事件]=–publicclassPersonsViewModel:ViewModelBase{//...privateBoolean_isDataLoaded;公共布尔IsDataLoaded{得到{返回_isDataLoaded;}私有集{_isDataLoaded=值;OnPropertyChanged("IsDataLoaded");}}publicvoidLoadDataAsync(){if(this.IsDataLoaded)返回;varbwLoadData=newBackgroundWorker();bwLoadData.DoWork+=(sender,e)=>e.Result=_personRepository.GetAll();bwLoadData.RunWorkerCompleted+=(sender,e)=>{this.Persons=(IEnumerable)e.Result;this.IsDataLoaded=true;};bwLoadData.RunWorkerAsync();}}publicclassPersonWindow:Window{privatereadonlyPersonsViewModel_personsViewModel;publicPersonWindow(IRepositorypersonRepository){_personsViewModel=newPersonsViewModel(personRepository);this.Loaded+=PersonWindow_Loaded;}privatevoidPersonWindow_Loaded(Objectsender,RoutedEventArgse){this.Loaded-=PersonWindow_Loaded;_personsViewModel.LoadDataAsync();我真的不喜欢这个解决方案,因为它强制ViewModel的用户调用LoadDataAsync方法–=[第三种解决方案:在ViewModel构造函数中加载数据]=–publicclassPersonsViewModel:ViewModelBase{//...publicPersonsViewModel(IRepositorypersonRepository){if(personRepository==null)thrownewArgumentNullException("personRepository");_personRepository=personRepository;这个.LoadDataAsync();}私有布尔值_isDataLoaded;公共布尔IsDataLoaded{得到{返回_isDataLoaded;}私有集{_isDataLoaded=值;OnPropertyChanged("IsDataLoaded");}}publicvoid(AsData)if(this.IsDataLoaded)返回;varbwLoadData=newBackgroundWorker();bwLoadData.DoWork+=(sender,e)=>e.Result=_personRepository.GetAll();bwLoadData.RunWorkerCompleted+=(sender,e)=>{this.Persons=(IEnumerable)e.Result;this.IsDataLoaded=true;};bwLoadData.RunWorkerAsync();在这个解决方案中,ViewModel的用户不需要调用额外的方法来加载数据,但它违反了单一职责原则,正如MarkSeeman在他的书“依赖注入”中所说:“让构造函数不受任何逻辑。SRP意味着成员应该只做一件事,现在我们使用构造函数来注入依赖项,我们宁愿保留它而没有其他问题。关于如何以正确的方式解决这个问题的任何想法?如果不确定如何绑定ViewModel当然,很难给出准确的答案。一种方法是拥有一个“导航INavigationAware”ViewModel(一种实现INavigationAware的ViewModel,如INavigationAware,并让您的导航服务在实例化ViewModel/View时绑定它们这就是Prism的FrameNavigationService的工作原理。即publicinterfaceINavigationAware{TaskNavigatedTo(objectparam);TaskNavigatedFrom(...)}publicclassPersonWindow:ViewModelBase,INavigationAware{}如果ViewModel实现了INavigationAware,那么在NavigatedTo中实现初始化代码,将使用导航服务中的INavigationAware。Windows应用商店的Prism参考:以上是C#学习教程:MVVM中的后台加载和构造函数注入。更多关于C#学习教程,希望大家多多关注~本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
