Home > Net >  Should I inject dbContext into WPF?
Should I inject dbContext into WPF?

Time:11-12

OLD WAY

Until now I created dbContext as follows, so the dbContext is short lived, as it should be (the dbContext is alive only for specific operations).

using (var dbContext = new MainDbContext())
{ ... }

NEW WAY

Now I try to use DI for the dbContext. For the time being I do not want to use any DI container just pure DI.

public partial class MainWindowViewModel 
{
    IMainDbContext dbContext;

    public MainWindowViewModel(IMainDbContext dbContext)
    {
        this.dbContext = dbContext;
    }    
}

My composition root is in OnStartup

private void OnStartup(object sender, StartupEventArgs e)
    {
        var mainWindowViewModel = new MainWindowViewModel(new MainDbContext());
        ...
    }

I do not like this new approach because the dbContext is always alive not just for a particular operation. 1. Is there an alternative?

I have several ViewModel. 2. Should I use the same dbContext instance for all of them?

The new approach always creates MainDbContext in the composition, though it is possible I will not press such a button in the GUI which needs MainDbContext. 3. Is there a workaround?

CodePudding user response:

Your question is primarily opinion-based, i.e. there is no right or wrong really.

In a N-tier enterprise application, the EF context should only live in the data access layer (DAL) on the server side. The client the typically consumes the database via a service layer that uses the context to fetch the data.

Whether you should use the same context for all view models depends on whether your DB operations span across several view models. Do you for example modify an entity using one view model and persit the changes by calling SaveChanges() in another one? Then it makes sense for the context to be shared among these two view models at least.

Same story for long-lived vs. short-lived contexts. It depends on your scenario. But if you inject the context into some view models, you probably want to register it as a singleton instance. You can always use a short-lived (non-injected) context in other view models if you need to.

  • Related