【发布时间】:2021-05-03 19:24:33
【问题描述】:
我正在为现有域层构建 Blazor 服务器前端。该层提供各种可注入服务来对 EF Core 存储库进行修改。为此,服务本身从(标准 Microsoft)DI 容器请求 DbContext。这适用于具有范围 DbContext 实例的常规 MVC.NET/Razor 页面,但作为 documented,这对于 Blazor 来说是有问题的。在 Blazor Server 应用程序中,我们希望使用 DbContextFactory 来生成用于操作的短期 DbContext 实例。
在同一个应用程序中同时拥有 DbContext 和 DbContextFactory 没有问题,但我很难理解如何调整我的服务。或者如果我什至需要?为了说明,这是当前代码:
我的页面:
@page “/items”
@inject ItemService ItemService
// somewhere in the code
ItemService.DoOperation(…)
我的服务
class ItemService
{
public ItemService(MyDbContext myDbContext)
{
…
}
public bool DoOperation(…)
{
…
_myDbContext.SaveChanges();
}
}
Startup.cs:
services.AddDbContext<MyDbContext>(options => …),
contextLifetime: ServiceLifetime.Transient,
optionsLifetime: ServiceLifetime.Singleton
);
services.AddDbContextFactory<MyDbContext>(options => …);
我已经根据this answer 中给出的示例更改了 DbContext 的生命周期,到目前为止,我还无法创建任何问题,但我并不完全理解这里的生命周期问题。如何设计我的服务以在 Blazor 和 MVC/Razor Pages 应用程序中以一种明显的方式良好运行?
【问题讨论】:
-
只是一个更新:在 EF Core 6 中,AddDbContextFactory 现在还注册了 DbContext,因此不再需要单独注入它们。
标签: c# asp.net-core entity-framework-core blazor .net-5