我使用autofac和mediatR在asp.net api2上开发了一个应用程序,目前面临着依赖注入的一些问题。
// This is registered in the global.asax file and working properly in the controller level
//i'm trying to register the entity framework context as instance per request
builder.RegisterType<EFContext>().InstancePerRequest();
但是,当通过MediatR管道发送命令时,我得到一个例外,因为MetdiatR服务提供者无法读取http请求范围。
下面的代码也位于全局asax文件中。
builder.Register<ServiceFactory>(context =>
{
var componentContext = context.Resolve<IComponentContext>();
return t => { object o;
return componentContext.TryResolve(t, out o) ? o : null; };
});
当调用服务定位器的委托函数时,它会抛出一个错误,指出没有带有与“AutofacWebRequest”匹配的标记的作用域可以从作用域中看到....
是否有任何工作要使mediatr ServiceFactory知道autofact InstancePerRequest范围?
使用InstancePerLifetimeScope
代替解析实体框架上下文。
我没有使用mediatR,但似乎它没有遵循请求响应模式,因为Autofac无法将任何Request Lifetime与之关联。
请注意,Autofac中请求范围和生命周期范围之间的区别仅在于Autofac将请求视为生命周期。
您可以从这里进一步了解范围,https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html