【发布时间】:2019-03-31 12:44:14
【问题描述】:
我正在实现队列触发的 azure 函数 - 我正在使用名为 Mediatr 的中介模式库来增强命令查询隔离 - 并根据以下内容在 Azure 函数中使用最新的运行时 (2.0.12382.0) 构造函数依赖注入教程 https://devkimchi.com/2019/02/22/performing-constructor-injections-on-azure-functions-v2/
对于每个 Azure 函数触发器,我调用 Mediatr CommandHandler 但我收到错误:
"在前一个操作完成之前在此上下文上启动了第二个操作。这通常是由使用相同 DbContext 实例的不同线程引起的,但是不能保证实例成员是线程安全的。这也可能是由嵌套的正在客户端评估的查询,如果是这种情况,请重写查询以避免嵌套调用。"
错误表明我正在尝试从并行任务访问 DbContext 的同一实例。但是我只有一个命令处理程序(Mediatr Handler)和一个查询处理程序。我正在为此使用构造函数注入
我尝试在启动时将 Meditr 服务更改为瞬态,但在 azure 函数模拟器中测试函数时仍然收到相同的错误
启动类
public class StartUp : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var connection = configuration.GetConnectionString("Default");
builder.Services.AddDbContext<CoreDBContext>(options =>
{
options.UseSqlServer(connection, p =>
{
p.MigrationsAssembly("B12Core.Persistence");
});
}
);
builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPreProcessorBehavior<,>));
builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPerformanceBehaviour<,>));
builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationBehavior<,>));
builder.Services.AddMediatR(p =>
{
p.AsTransient();
}, typeof(CreateMessageCommand).GetTypeInfo().Assembly);
}
}
完全错误
System.Private.CoreLib:执行函数时出现异常:Function1。 Microsoft.EntityFrameworkCore:在前一个操作完成之前在此上下文上启动了第二个操作。这通常是由使用相同 DbContext 实例的不同线程引起的,但是不能保证实例成员是线程安全的。这也可能是由在客户端上评估嵌套查询引起的,如果是这种情况,请重写查询以避免嵌套调用。
【问题讨论】:
-
我遇到了同样的问题。显然挖掘的依赖项仍然无法正常工作。 github.com/Azure/azure-functions-host/issues/…
标签: entity-framework-core azure-functions dbcontext azure-functions-runtime mediatr