在我的asp.net core mvc项目中,我通常会使用这个服务来进行业务操作
services.AddDbContextPool<AppDbContext>(option => {
option
.UseMySql(
Configuration.GetConnectionString("SqliteConstr"),
new MySqlServerVersion(new Version(5, 5, 62)),
//错误重试
MysqlOpt => MysqlOpt.EnableRetryOnFailure()
);
});
services.AddScoped<GameService>();
public class GameService
{
private AppDbContext DbContext { get; set; }
public GameService(AppDbContext dbContext)
{
//DbContext = contextFactory.CreateDbContext();
DbContext = dbContext;
}
public async Task<Game[]> GetGamesAsync()
{
return await DbContext.Games.ToArrayAsync();
}
}
现在我打算迁移到blazor服务器,但是官方教程要求我使用工厂模式将DbFactory注入到blazor组件中,如下所示,我对blazor不是很熟悉,这是blazor中的要求吗?
services.AddDbContextFactory<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
// in blazor page core
@inject ItemService ItemService
using var context = DbFactory.CreateDbContext();
Filters.Loading = true;
var contact = await context.Contacts.FirstAsync(
c => c.Id == Wrapper.DeleteRequestId);
if (contact != null)
{
context.Contacts.Remove(contact);
await context.SaveChangesAsync();
}
Filters.Loading = false;
await ReloadAsync();
AddScoped
在 Blazor Server 中几乎相当于AddSingleton
在普通的基于 http 的任何内容中(webapi、asp mvc、razor 页面等)。不完全是,但每个用户都会得到一个,而且只有一个DbContext
。 Blazor 服务器通过 WebSocket 连接工作。没有传统的请求生命周期。有一根管道不断地来回发送东西。因此,您的作用域服务将用于该连接,直到它消失。多个 UI 操作最终将使用完全相同的实例进行查询。这可能会导致问题,但如果您仅使用单个查询来测试它,那么它肯定会起作用。
使用工厂并创建DbContext
当需要的时候可以很好地解决这个问题。
你可以重写你的GameService
使用工厂。
public class GameService
{
private readonly IDbContextFactory<ApplicationDbContext> factory;
public GameService(IDbContextFactory<ApplicationDbContext> factory)
{
this.factory = factory;
}
public async Task<Game[]> GetGamesAsync()
{
using (var context = factory.CreateDbContext()) {
return await context.Games.ToArrayAsync();
}
}
}
然后你可以注入你的GameService
作为单例或范围服务。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)