WPF / EntityFramework Context Lifetime WPF / EntityFramework Context Lifetime wpf wpf

WPF / EntityFramework Context Lifetime


In your application there is only single unit of work but that is not the purpose of a unit a work. Instead, you need to create a unit of work each time "you work with the database". In your case the UnitOfWork should not be part of the MEF container but you can create a UnitOfWorkFactory and inject it from the container. Then the services can create a UnitOfWork each time "work has to be done" with the database:

using (var unitOfWork = unitOfWorkFactory.Create()) {  // Do work ...  unitOfWork.Save();}

I have modified UnitOfWork so it implements IDisposable. This will allow you to dispose the EF context and also perhaps rollback a transaction if Save was not called. If you have no need for the extra transaction handling you can even get rid of the UnitOfWork class because it simply wraps the EF context and instead you can used the EF context as a unit of work directly.

This change will force you to modify how the service and the repositories are structured but you really have to because your issue is that you have a single unit of work that exists for the entire duration of the application.


Outline clearly distinguished use cases, which would maintain own lifetime scope. This could help preventing other resources leaks as well (which are pretty frequent when using WPF).

Consider generic algorithm:

  • Initialize lifetime scope.
  • Using scope:
    • Allocate views and other WPF resources, allocate business layer, data access (UoW, context, repo).
    • Load data from db and display it to user.
    • Wait for user action (1).
    • Make some changes or load even more data from DB.
    • Update data representation for user.
    • Go to (1) until scenario is complete.
  • Dispose scope, de-allocate resources.

The problem is that your scope currently is your application.

Now imagine that you manage scope at view level. You allocate, display view, get user's input, save changes and then the whole object tree is disposed at once.

Obviously, you should be flexible with scopes. Sometimes it can be useful to use it at view level (like "Edit item"), sometimes it could spread across several views (like wizard, for example). You can even maintain data-driven scopes (imagine you open a project in Visual Studio; begin lifetime scope to manage all resources, which should be available while project 'lives').