我在asp.net api2上用autofac和mediatR开发了一个应用程序,目前面临一些依赖注入的问题。
// 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作用域?
发布于 2019-02-20 16:00:48
请改用InstancePerLifetimeScope来解析实体框架上下文。
我没有使用mediatR,但它似乎不遵循请求响应模式,因此Autofac不能将任何请求生命周期与其关联。
请注意,Autofac中的请求作用域和生存期作用域之间的区别只是Autofac会将请求视为生存期。
你可以从这里进一步了解作用域,https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html
https://stackoverflow.com/questions/54773555
复制相似问题