【发布时间】: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