编辑:
正如 James Bradt 在下面的帖子中提到的那样,Autofac 软件包现已更新以解决此问题,因此将来遇到此线程的任何人都应该先尝试新软件包 :)
基本上,使用新包,您只需要在 global.asax.cs 中执行此操作:
GlobalConfiguration.Configuration.DependencyResolver = new Autofac.Integration.WebApi.AutofacWebApiDependencyResolver(container);
/编辑
我刚刚遇到了同样的问题——我可以通过创建一个简单的 IDependencyResolver 实现来解决这个问题,该实现包含现有的 AutofacDependencyResolver。
正如类名所暗示的,我将此视为临时解决方案 - BeginScope 和 Dispose 方法需要一些工作,并且显然不适合生产环境,但这允许我继续开发,直到出现适当的解决方案。
因此,有了这些警告,IDependencyResolver 实现看起来像这样:
public class TemporaryDependencyResolver : IDependencyResolver
{
private readonly AutofacDependencyResolver _autofacDependencyResolver;
public TemporaryDependencyResolver(AutofacDependencyResolver autofacDependencyResolver)
{
_autofacDependencyResolver = autofacDependencyResolver;
}
public void Dispose()
{
}
public object GetService(Type serviceType)
{
return _autofacDependencyResolver.GetService(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _autofacDependencyResolver.GetServices(serviceType);
}
public IDependencyScope BeginScope()
{
return this;
}
}
我在 Global.asax.cs 中这样设置:
var container = builder.Build();
var resolver = new AutofacDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = new TemporaryDependencyResolver(resolver);