The request lifetime scope cannot be created because the HttpContext is not available
Posted on 2017-10-13 11:29 冰碟 阅读(1283) 评论(0) 编辑 收藏 举报项目中应用了Autofac,在Global轮询处理Job的时候,需要获取现有得Service,而这些Service已经通过Autofac进行了配置,所以理所应当的用下面的代码去获取了。
DependencyResolver.Current.GetService<ClinicalCaseService>();
结果出现问题了,直接抛出错误“The request lifetime scope cannot be created because the HttpContext is not available”。
结果疯狂的stackoverflow(地址:https://stackoverflow.com/questions/21804857/autofac-the-request-lifetime-scope-cannot-be-created-because-the-httpcontext-i),查找解决方案。
因为在AutofacDependencyResolver.Current内部GetService的时候需要HttpContext,所以会直接抛出错误。
解决方案:
1,autofac
var resolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
2,获取Service
ClinicalCaseService = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof (ClinicalCaseService)) as ClinicalCaseService;