I know this might be a "style of coding" question but at this point I'm really confused. Currently I'm trying to follow the MVVM pattern (ViewModel, Repository, Controller etc.)
But who should initiate a connection to the source of data? Especially when more than one Controller needs an active connection?
There aren't that many possibilities out there - either every Controller itself opens a new connection, the corresponding ViewModel opens the connection and passes it to the repository which in turn passes it to it's controller - or the connection gets instantiated even earlier (e.g. StartUp.cs).
I know there is no "perfect" solution but I hope to get some inspiration and maybe a good / best practice.
Update 1
Example Code:
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
}
}