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

时间:2015-01-29 06:54:13

标签: c# wpf database mvvm responsibility

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

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

没有那么多的可能性 - 每个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
 }
}

2 个答案:

答案 0 :(得分:3)

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

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

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

<强>更新

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

http://martinfowler.com/eaaCatalog/repository.html - 本文介绍了模式&#34;存储库&#34;。他实现了类似集合的界面,并隐藏了数据访问的功能。因此在存储库中应该创建连接。

答案 1 :(得分:3)

我认为你将MVC与MVVM混为一谈:

MVVM overview MVC overview

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

 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;
     }