Windows-XAML / Template10

Making Windows 10 apps great again
Apache License 2.0
1.41k stars 388 forks source link

Where to place the Database Viewmodel #366

Closed alanb6448 closed 8 years ago

alanb6448 commented 8 years ago

Hi, I am just starting to use T10 and basically modifying the HamburgerMenu example. I have data stored in an sqllite database and access it through a datamanager class whoose only parameter is a connection string. Everything else is encapsulated in the class and access via properties.

The final app will have several pages each requiring access to the database. So not sure best way to do this mt thoughts are to have the database manager in Shell and pass refs to it into viewmodel associated with each page. Is there a better way of doing it?

Thanks Alan

AmitBhatnagar24 commented 8 years ago

Might want to think about your architecture here.

A common approach is to use a Dependency Injection framework, (such as Microsoft's Unity, or SimpleIOC that comes with MVVMLight, and there are many others). You would inject a your "data access service" in the view models that require them.

JerryNixon commented 8 years ago

I would create a database in /Data/Database.sql I would create a database service in /Services/DataService/DataService.cs In DataService.cs I would have all the CRUD operations Then you can re-use DataService in more than one ViewModel This make sense?

Also, you can use dependency injection if you want, but you can also just new-up a DataService in each ViewModel. That's the simplest, getting starred approach. This lets you update the code in your DataService, knowing that every ViewModel gets the benefit. Moreover, it also means you can swap out your DataService underlying logic so point to the cloud if you want, without changing or updating your ViewModels. It's a very smart approach because it allows you keep things separate, test them independently, and so on.