【发布时间】:2014-02-15 23:00:13
【问题描述】:
小问题:Same as this unanswered problem
长问题:
我刚刚将一些代码从使用 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 依赖解析器设置为同一个容器之前,这不起作用:
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 天内以赏金奖励现有答案
【问题讨论】:
-
但是 HttpContext 确实存在于您的 Workflow 项目中吗?你可以创建一个容器并尝试直接从容器中解析
IUserRepo,而不是去.Current?InstancePerLifetimeScope()也比InstancePerHttpRequest好。
标签: c# asp.net-mvc asp.net-web-api autofac dependency-resolver