Lifetime of scoped EF Core DbContext in WPF

Viewed 720

I want to use EF Core with the .NET Core dependency injection in a .NET Core 3.1 WPF application.

In ASP.NET, the lifetime of the scoped DbContext would be one HTTP request, but in WPF, it would be the lifetime of the whole application, which is not recommended.

So how do I manage the lifetime of the DbContext in a WPF .NET Core application?

1 Answers

I Suggest to define it this way:

services.AddDbContext<AppDbContext>(options => options
        .UseSqlServer(configuration.GetConnectionString("LocalDB")), ServiceLifetime.Transient, ServiceLifetime.Transient);

This way each Model has its own DbContext.

Another Solution would be to declare Singleton DbContextFactory and call its Create method to create new DbContext per use.

Related