【问题标题】:WPF - MVVM - Who is responsible for a new DataProvider Connection?WPF - MVVM - 谁负责新的 DataProvider 连接?
【发布时间】:2015-03-28 07:40:26
【问题描述】:

我知道这可能是一个“编码风格”的问题,但在这一点上我真的很困惑。目前我正在尝试遵循 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
 }
}

【问题讨论】:

  • 为什么要在类之间共享数据库连接?只需在需要时打开和关闭。当然用一些接口抽象出数据库逻辑,注入到需要连接的地方。如果你认为我在说别的;那么请发布代码。否则很难理解你的想法。
  • 我会分享代码 - 如果它存在的话。这更像是一个理论问题。当然我会用一个接口抽象数据库逻辑——我会试着写一段代码来告诉你我想知道的。

标签: c# wpf database mvvm responsibility


【解决方案1】:

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

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

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

更新:

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

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

【讨论】:

  • 谢谢你的链接,它真的很有趣 - 但我不明白为什么我应该误解 MVVM - 上面的代码 - 如前所述 - 只是一个示例假人,用于向您展示我想要的知道。我知道在 MVVM 或类似的东西中没有“规则”。
【解决方案2】:

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

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

【讨论】:

  • 非常好的答案,谢谢!因此,当我定义一个需要存储库接口的 ViewModel 时,我必须在相应视图的代码后面声明/实例化我的 ViewModel,不是吗?使用没有任何参数的构造函数,我可以在 XAML 中内联实例化 ViewModel。
  • 尽量让 view.xaml.cs 文件为空,把你的视图模型放在不同的类上,我建议你使用一些 MVVM 框架来帮助你做样板,比如 MVVM Light .也看看像apuntanotas.codeplex.com这样的例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 2021-06-05
  • 2012-10-04
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
相关资源
最近更新 更多