简短的问题:与这个未回答的问题相同
长问题:
我刚刚将一些代码从使用 Autofac 的 MVC 4 + Web Api 解决方案移植到我的新解决方案中,该解决方案也使用 Autofac 但仅使用 Web Api 2(没有 MVC 5.1 项目,只是一个 Web api)。
在我之前的解决方案中,我有 MVC4 和 Web Api,所以我有 2 个 Bootstrapper.cs 文件,每个文件一个。我只复制了新项目的 Web Api 引导程序。
现在,我在新解决方案中有 2 个需要提取依赖项的其他项目。让我们假设我必须使用DependencyResolver.Current.GetService<T>()
它,尽管它是一种反模式。
起初,直到我将 MVC Dependency Resolver 设置为同一个容器,这才起作用:
GlobalConfiguration.Configuration.DependencyResolver =
new AutofacWebApiDependencyResolver(container);
//I had to pull in Autofac.Mvc and Mvc 5.1 integration but this line fixed it
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
奇怪的是,这样做只会在其中一个项目中修复它!情况如下:
Solution.Web project
Bootstrapper.cs that registers both dependency resolvers for web api and mvc.
Solution.ClassLib project
var userRepo = DependencyResolver.Current.GetService<IUserRepo>(); //Good! :)
Solution.WindowsWorkflow project
var userRepo = DependencyResolver.Current.GetService<IUserRepo>(); //Throws exception :(
例外情况是:无法创建请求生命周期范围,因为 HttpContext 不可用。
现在在我们开始指责工作流之前,只要知道我在另一个解决方案中这个精确的设置工作得很好,工作流能够很好地使用 DependencyResolver。所以我怀疑这与使用较新版本的 Autofac 以及工作流异步运行的事实有关(就像我链接到的关于异步代码的问题一样)
我尝试将所有注册码切换为使用InstancePerLifetimeScope()
,而不是InstancePerHttpRequest()
尝试创建一个范围:
using (var c= AutofacDependencyResolver.Current
.ApplicationContainer.BeginLifetimeScope("AutofacWebRequest"))
{
var userRepo = DependencyResolver.Current.GetServices<IUserRepo>();
}
但它并没有改变例外。进一步分解代码是确切的罪魁祸首:
var adr = AutofacDependencyResolver.Current; //Throws that exception
真的需要克服这个花太多时间卡住的问题。将在 2 天内以赏金奖励现有答案