Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM + Entity Framework architecture confusion

I'm using Prism framework with EF in WPF application.

ViewModel:

  • keeps service references (passed by unity container).

Services:

  • are providing "high level" operations with data
  • keeps reference of Repository, which provides basic CRUD operations with database (single table per repository).

Repository:

  • every method in repository uses the "using" pattern, where I work with short lived object context.

This is where i got stuck: after object context is disposed, I can not work with mapped properties no longer. My database model is complex (many related tables) and many .Include() calls when retrieving data keeps code dirty.

After reading several threads, I discovered that "unit of work" pattern is probably what I need.

Here comes my question:

Who keeps reference of unit of work (and therefore context)? If I choose context per view approach, viewModel should have context reference. How can I inject unit of work to my services then? Or should I create new instance of Service in ViewModel and pass context in constructor parameter?

like image 219
yurislav Avatar asked Oct 21 '22 07:10

yurislav


1 Answers

We're using a similar architecture in a project:

  • Each ViewModel gets its own Service object which gets injected in the constructor (at least the top level ones that directly correspond to a View. Some hierarchical ViewModels may reuse their parent's Service, but let's keep it simple here).

  • By default, each Service operation creates a new context, but...

  • Services have BeginContext and EndContext methods which can be called by the ViewModels to keep the context open over multiple operations.

This worked pretty well for us. Most of the time we call BeginContext when a View is opened and EndContext when it is closed.

like image 167
Daniel Sklenitzka Avatar answered Oct 27 '22 20:10

Daniel Sklenitzka