Do I need to be specifying a lifetime of transient? Or is this set to transient already for Blazor?
You can check this article: ASP.NET Core Blazor Server with Entity Framework Core (EF Core)
EF Core provides the AddDbContext extension for ASP.NET Core apps that registers the context as a scoped service by default. In Blazor Server apps, scoped service registrations can be problematic because the instance is shared across components within the user's circuit. DbContext isn't thread safe and isn't designed for concurrent use. The existing lifetimes are inappropriate for these reasons:
- Singleton shares state across all users of the app and leads to inappropriate concurrent use.
- Scoped (the default) poses a similar issue between components for the same user.
- Transient results in a new instance per request; but as components can be long-lived, this results in a longer-lived context than may be intended.
So, in Blazor server application, you can use the DbContext factory to create the DbContext instance for each operation.
for example, you can create the DbContext factory like this:
builder.Services.AddDbContextFactory<ContactContext>(opt =>
opt.UseSqlite($"Data Source={nameof(ContactContext.ContactsDb)}.db"));
then, inject the factory into your components, and create the DbContext instance, like this:
@inject IDbContextFactory<ContactContext> DbFactory
and
private async Task DeleteContactAsync()
{
using var context = DbFactory.CreateDbContext();
Filters.Loading = true;
if (Wrapper is not null && context.Contacts is not null)
{
var contact = await context.Contacts
.FirstAsync(c => c.Id == Wrapper.DeleteRequestId);
if (contact is not null)
{
context.Contacts?.Remove(contact);
await context.SaveChangesAsync();
}
}
Filters.Loading = false;
await ReloadAsync();
}
Then, the context is disposed when the component is disposed:
public void Dispose()
{
Context?.Dispose();
}
Note: As you said, the DbContextFacotry's default lifetime is Singleton, not the DbContext. Notice that the DbContext instances created in this way are not managed by the application's service provider and therefore must be disposed by the application.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion