gpt4 book ai didi

wpf - MVVM 和 StructureMap 使用

转载 作者:行者123 更新时间:2023-12-04 13:43:26 29 4
gpt4 key购买 nike

我的 MVVM 应用程序中有相当多的父细节 ViewModel。像这样的东西:

SchoolsViewModel
+- SchoolViewModel
+- LessonViewModel
+- PupilsViewModel
+- PupilViewModel
+- TeacherViewModel
+- PupilsViewModel
+- PupilViewModel
+- LessonsViewModel
+- TeachersViewModel

等等...

此外,单个 View 模型可以出现在多个地方,这取决于用户是按类(class)浏览还是按学生浏览等。

每个 subview 模型都是由父 View 模型创建的,因此很多 View 模型都需要传入 subview 模型的依赖项。例如 SchoolsViewModel 的构造函数可能是:
SchoolsViewModel(ISchoolsRepository schoolsRepository,
ILessonsRepository lessonsRepository,
IPupilsRepository pupilsRepository,
ITeachersRepository teachersRepository,
...)

现在,使所有这些变得可管理的常用方法是使用 DI 框架(例如 StructureMap)将所有必需的参数传递给 View 模型。但是,因为在这种情况下,我的应用程序通常只会创建 SchoolsViewModel,因此用途有限。

我的第一个问题是,在这种情况下,您是让 SchoolsViewModel 将每个依赖项传递给每个 subview 模型,还是让每个 View 模型使用 ObjectFactory.GetInstance() 来创建 subview 模型?或许通过一个工厂类来抽象出对DI框架的依赖?

还有一个与此相关的问题: MVVM: locating other ViewModels

编辑:因为我想要更多的意见,所以我对此进行了悬赏。

最佳答案

另一种选择...

看看这个 LessonViewModel。它只依赖于 Pupils 和 Teachers,并且对 PupilParents 或任何其他子对象一无所知。

public class LessonViewModel
{
private IPupilsFactory _pupilsFactory;
private ITeachersFactory _teachersFactory;

public LessonViewModel(IPupilsFactory pupilsFactory, ITeachersFactory teachersFactory)
{
_pupilsFactory = pupilsFactory;
_teachersFactory = teachersFactory;
}

public string Name { get; set; }
public List<string> PupilNames { get; set; }
public string TeacherName { get; set; }

public PupilViewModel GetPupil(string name)
{
return _pupilsFactory.Create(name);
}

public TeacherViewModel GetTeacher()
{
return _teachersFactory.Create(TeacherName);
}
}

类(class)工厂包含所有必需的依赖项,但它也对 PupilParents 一无所知。
public interface ILessonsFactory
{
LessonViewModel Create(string name);
}

public class LessonsFactory : ILessonsFactory
{
private ILessonsRepository _lessonsRepository;
private IPupilsFactory _pupilsFactory;
private ITeachersFactory _teachersFactory;

public LessonsFactory(ILessonsRepository lessonsRepository, IPupilsFactory pupilsFactory, ITeachersFactory teachersFactory)
{
_lessonsRepository = lessonsRepository;
_pupilsFactory = pupilsFactory;
_teachersFactory = teachersFactory;
}

public LessonViewModel Create(string name)
{
Lesson lesson = _lessonsRepository.Read(name);

return new LessonViewModel(_pupilsFactory, _teachersFactory) {
Name = lesson.Name,
PupilNames = lesson.PupilNames,
TeacherName = lesson.TeacherName
};
}
}

关于wpf - MVVM 和 StructureMap 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1136023/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com