我目前正在 .NET Core 中开发 Azure Function 应用程序,并尝试为请求添加事务。问题是,当函数调用在
context.Database.BeginTransaction(...)
调用和 transaction.CommitAsync(...)
调用之间执行工作时,另一个函数调用无法保存到数据库并超时:
[2024-01-04T07:23:29.957Z] An exception occurred in the database while saving changes for context type 'MyContext'.
[2024-01-04T07:23:29.957Z] System.InvalidOperationException: An exception has been raised that is likely due to a transient failure.
[2024-01-04T07:23:29.957Z] ---> Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
[2024-01-04T07:23:29.958Z] ---> Npgsql.NpgsqlException (0x80004005): Exception while reading from stream
[2024-01-04T07:23:29.958Z] ---> System.TimeoutException: Timeout during reading attempt
当“长时间运行”的函数调用没有被事先调用时,这个其他函数调用可以保存得很好。所以我认为打开的事务正在阻塞其他函数调用中的
DbContext
。
我们的
DbContext
注册如下:
builder.Services.AddDbContext<MyContext>(
options => options
.UseNpgsql(dbConnStr)
.UseSnakeCaseNamingConvention());
据我了解,每个函数调用都应该获得自己的依赖注入作用域,就像在 ASP .NET Core 中一样,“相同”的设置可以正常工作。
我错过了什么吗?
试试这个,
builder.Services.AddDbContext<MyContext>(
options => options
.UseNpgsql(dbConnStr)
.UseSnakeCaseNamingConvention(),
ServiceLifetime.Scoped
);
通过添加“ServiceLifetime.Scoped”,您可以确保为每个范围创建 DbContext 的新实例。