AutofacInstanceContext.Current为空,我不明白为什么
我正在使用Autofac作为IoC容器和MediatR作为中介来执行我的请求&命令的WCF项目。AutofacInstanceContext.Current为空,我不明白为什么
WCF契约的“基础”实现采用IMediator
的实例作为依赖关系,以将与每个请求关联的工作委托给关联的处理程序。我也有几个装饰器,我堆叠基本的实现,如授权和错误处理。
根据this page of Autofac documentation的规定,当您在服务实现上使用装饰器时,为了满足WCF内部需要使用MultitenantServiceImplementationDataProvider
。没有更多的多租户相关的需要,所以它只是包括:
AutofacServiceHostFactory.ServiceImplementationDataProvider = new MultitenantServiceImplementationDataProvider();
此外,在.svc
我指定的接口的限定名,因为它是由Autofac和支持我在上面装饰我的基本实现。
现在,到MediatR。
MediatR使用服务位置在提供请求时实例化适当的处理程序。更具体地说,它依赖于CSL。
没有问题,因为Autofac提供了一个bridge to support CSL。
“棘手”的部分依赖于我的处理程序将DbContext
作为依赖关系,并且我希望它们在每个WCF请求之后由Autofac处置。
因此,AutofacServiceLocator
必须被赋予为特定请求创建的范围,因为根范围不会被丢弃,也不会是DbContext
实例。
Autofac为您提供了AutofacInstanceContext.Current
静态属性,它等价于ASP.NET MVC中的AutofacDependencyResolver.RequestLifetimeScope
。
到目前为止好,这里是我如何注册ServiceLocatorProvider
的Mediator
类呈现出depedency:
builder
.Register(x => new ServiceLocatorProvider(() => new AutofacServiceLocator(AutofacInstanceContext.Current.OperationLifetime)))
.InstancePerLifetimeScope();
它可以在我的开发如预期,但我得到一个NullReferenceException
上的临时环境,我不真的知道在哪里寻找 - GoogleBing没有提供相关结果。
只有从两个环境不同的东西:
- HTTP在我上的临时ENV箱VS HTTPS。
-
debug
属性<system.web>
元素在分段环境中设置为false。
而就是这样...
NET框架相同,4.5.2。
任何人有想法? 谢谢!
通过改变固定它:
builder
.Register(x => new ServiceLocatorProvider(() => new AutofacServiceLocator(AutofacInstanceContext.Current.OperationLifetime)))
.InstancePerLifetimeScope();
与
builder
.Register(x =>
{
var serviceLocator = new AutofacServiceLocator(AutofacInstanceContext.Current.OperationLifetime);
return new ServiceLocatorProvider(() => serviceLocator);
}
.InstancePerLifetimeScope();
我无法准确地告诉你为什么它没有工作,但我想通过MediatR在内部执行lambda表达式() => new AutofacServiceLocator(AutofacInstanceContext.Current.OperationLifetime)
的时间,这为时已晚,并且当前操作上下文已被处置或释放。
任何洞察力仍将不胜感激!
您正在使用哪个版本的MediatR?它已经从通用服务定位器转向了工厂方法代表。https://github.com/jbogard/MediatR/commit/82ce595fcd5d265862bf80127fee932902c3d8cd –
我正在使用最新的稳定版本1.0.0。 Jimmy说,如果我没有弄错的话,他将不会使2.0稳定,直到.NET Core稳定。无论如何,我认为这对我的问题不会有太大的改变 –