Skip to content

Blazor Identity templates and CRUD scaffolding should use the DbContextFactory #54539

Closed as not planned
@sonnemaf

Description

@sonnemaf

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe the problem.

The Identity templates and CRUD scaffolding of Blazor 8 are not using the guidelines for using EF Core in Blazor apps.

I think this is bad because this will cause issues because the DbContext which is used in the current solution is a scoped service. In server-side Blazor 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 template and scaffolding should be a best practice and they are not.

Describe the solution you'd like

Register a DbContextFactory service in the Program.cs

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

This should be:

builder.Services.AddDbContextFactory<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

This will also mean that the Pages and maybe also the AddIdentityCore services start using the Factory. This won't be easy.

The same for the scaffolded CRUD pages. They should get a IDbContextFactory<T> injected and not a DbContect. You will have to create a DbContext that exists for the lifetime of a component.

If this is done the developers will use this solution too for their own components.

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions