1

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

但是谁应该发起与数据源的连接呢?特别是当多个控制器需要活动连接时?

那里没有那么多可能性 - 每个控制器本身打开一个新连接,相应的 ViewModel 打开连接并将其传递给存储库,然后将其传递给它的控制器 - 或者连接被实例化甚至更早(例如 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
 }
}
4

2 回答 2

4

我认为您将 MVC 与 MVVM 混淆了:

MVVM 概述 MVC 概述

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

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

或者甚至更好地将存储库接口注入到您的 ViewModel 中,以获得干净、解耦和可测试的实现:

public ViewModel(IPersonRepository personRepo, IDepartmentRepository depRepo)
    {
       Person.PersonRepository pR = personRepo;
       Department.DepartmentRepository dR = depRepo;
     }
于 2015-01-29T09:59:15.857 回答
3

我认为您误解了 MVVM 模式。阅读这篇文章:

https://msdn.microsoft.com/en-us/magazine/dd419663.aspx

它应该有助于更好地理解 MVVM。

更新:

存储库打开连接。如果使用 ORM 访问数据库(EF、NHibernate),它们通常使用连接池。如果您不使用 ORM,那么您可以实现池。

http://martinfowler.com/eaaCatalog/repository.html - 本文描述了“存储库”模式。他实现了类似集合的接口,并隐藏了数据访问的特性。因此,应在存储库中创建连接。

于 2015-01-29T08:04:30.113 回答