gpt4 book ai didi

c# - WPF - MVVM - 谁负责新的 DataProvider 连接?

转载 作者:搜寻专家 更新时间:2023-10-30 21:46:40 32 4
gpt4 key购买 nike

我知道这可能是一个“编码风格”问题,但此时我真的很困惑。目前我正在尝试遵循 MVVM 模式(ViewModel、Repository、Controller 等)

但是谁应该发起与数据源的连接呢?尤其是当多个 Controller 需要一个事件连接时?

没有那么多可能性——要么每个 Controller 自己打开一个新连接,相应的 ViewModel 打开连接并将其传递给存储库,存储库又将其传递给它的 Controller ——或者连接更早地实例化(例如 StartUp.cs)。

我知道没有“完美”的解决方案,但我希望能得到一些启发,也许还有一个好的/最佳实践。

更新 1

示例代码:

namespace Question {
class ViewModel {

Person.Person p;
Department.Department d;

Person.PersonRepository pR;
Department.DepartmentRepository dR;

// Here in the VM both classes (Person and Department) intersect - should I inject an instance of a "IDataProvider" from here into the Repositorys?
// If so, I'd have to pass it to the repository which has to pass it to it's controller.
}
}

namespace Question.Person {
class Person {
// Person Model
}

class PersonRepository {
// This class does whatever a repository does and delegates database query to it's controller
}

class PersonController {

// Or should the Controller itself instantiate a new "IDataProvider" ?

// This class needs a connection to the databse to execute querys
}
}

namespace Question.Department {

class Department {
// Department Model
}

class DepartmentRepository {
// This class does whatever a repository does and delegates database query to it's controller
}

class DepartmentController {
// This class needs a connection to the databse to execute querys
}
}

最佳答案

我认为您混淆了 MVC 和 MVVM:

MVVM overview MVC overview

ViewModel 负责从模型中检索信息,使用从数据库中获取数据的存储库,您在这里不需要 Controller 。

 public ViewModel()
{
Person.PersonRepository pR;
Department.DepartmentRepository dR;
}

或者更好inject a repository interface进入您的 ViewModel 以获得干净、解耦和可测试的实现:

public ViewModel(IPersonRepository personRepo, IDepartmentRepository depRepo)
{
Person.PersonRepository pR = personRepo;
Department.DepartmentRepository dR = depRepo;
}

关于c# - WPF - MVVM - 谁负责新的 DataProvider 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28208631/

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