Is it safe to inject the DbContext service into a Razor component of an ASP.NET Core project?

Viewed 809

I have an existing ASP.NET Core (MVC) project. Part of my app requires client interactivity, so I've added support for Razor components. For using Razor components in my existing MVC project, I have:

  1. Added server-side Blazor in the ConfigureServices() method:
...
services.AddServerSideBlazor()
  1. Mapped the Blazor SignalR Hub in the Configure() method:
...
app.UseEndPoints(endpoints =>
{
    ...
    endpoints.MapBlazorHub();
});
...
  1. I also added an _Imports.razor file to my application root.

I'm planning to include the Razor components via the <component> tag in my views managed by controllers:

<component type="typeof(App)" render-mode="ServerPrerendered">

I want to enable database operations using EF Core in my Razor component. I have added my AppDbContext service to the DI container using the AddDbContext() method in Startup.cs. I was either planning to:

  • Inject my DB Context using the @inject directive directly in the component OR
  • pass it as a parameter to the component by first injecting the DB Context into my parent MVC view.

However, this is discouraged in this page of the documentation:

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 documentation states that it is the case for Blazor server apps. But what about an ASP.NET Core application that just uses Razor components?

0 Answers
Related