a question about DbContext's Lifetime
See original GitHub issuewhen API access more some access has error An unhandled exception was thrown by the application. System.InvalidOperationException: A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913. some access is success
when I restart service it’s will be ok;
webapi:
[HttpPut("{id}")]
[DisplayName("PutProduct")]
public async Task<Response<bool>> PutProduct(long id, [FromBody] UpdateChProductModel data)
{
var temp = await _context.ChProducts.FirstOrDefaultAsync(x => x.Id == id);
if (temp == null)
return ResultBuilder.FailResult(false, "product is not exist");
temp.Status = data.Status;
temp.PurPrice = data.PurPrice;
temp.LastUpdate = DateTime.Now;
await _context.SaveChangesAsync();
await _operateLogSvr.SaveLog(_curUserHelp.UserInfo.Id, LogType.ChProd,
_curUserHelp.UserInfo.Name + "PutProduct:" + JsonSerializer.Serialize(temp));
return ResultBuilder.SuccessResult(true, "success");
}
injection:
private readonly QYSDbContext_context;
private readonly IOperateLogService _operateLogSvr;
private readonly CurUserHelp _curUserHelp;
/// <summary>
/// Product
/// </summary>
/// <param name="context"></param>
/// <param name="operateLogSvr"></param>
/// <param name="curUserHelp"></param>
public ProductController(QYSDbContext context, IOperateLogService operateLogSvr, CurUserHelp curUserHelp)
{
_context = context;
_operateLogSvr = operateLogSvr;
_curUserHelp = curUserHelp;
}
IOperateLogService’s info:
public class OperateLogService : IOperateLogService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly CommLogNo _commLogNo;
public OperateLogService(IServiceScopeFactory serviceScopeFactory, CommLogNo commLogNo)
{
_serviceScopeFactory = serviceScopeFactory;
_commLogNo = commLogNo;
}
/// <summary>
/// add
/// </summary>
/// <param name="userId"></param>
/// <param name="type"></param>
/// <param name="remark"></param>
/// <returns></returns>
public async Task SaveLog(long userId, LogType type, string remark)
{
var operateLog = new OperateLog
{
Id = _commLogNo.NewId(),
Type = type,
UserId = userId,
Remark = remark,
CreateTime = DateTime.Now,
};
using var scope = _serviceScopeFactory.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<QYSDbContext>();
await context.OperateLogs.AddAsync(operateLog);
await context.SaveChangesAsync();
}
}
AddDbContext:
services.AddDbContextPool<QYSDbContext>((p, options) =>
{
var svr = p.GetService<SaveChangeTrigger>();
options.AddInterceptors(svr);
options.UseMySql(_configuration.GetValue<string>("ConnectionStrings:cgmysql"),
ServerVersion.AutoDetect(_configuration.GetValue<string>("ConnectionStrings:cgmysql")));
});
why this error is happened in OperateLogService, I use IServiceScopeFactory
how can I fixed it
change AddDbContextPool to AddDbContext and set ServiceLifetime to ServiceLifetime.Transient or set scope.ServiceProvider.GetRequiredService to scope.ServiceProvider.GetService ?
Issue Analytics
- State:
- Created a year ago
- Comments:5 (2 by maintainers)
Closing for now, can reopen if the details are provided.