var resolver = new AutofacWebApiDependencyResolver(container); configuration.ServiceResolver.SetResolver(resolver);
更新到ASP.NET MVC4(RC)后,我得到以下错误:
‘System.Web.Http.HttpConfiguration’ does not contain a definition for
‘ServiceResolver’ and no extension method ‘ServiceResolver’ accepting
a first argument of type ‘System.Web.Http.HttpConfiguration’ could be
found (are you missing a using directive or an assembly reference?)
看到这些接口已经改变了(http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver)后,我意识到,但我不知道如何应用这个改变如何使用Autofac.
我需要等待Autofac的新版本,还有另一种方式可以超越这个.
解决方法
编辑:
正如詹姆斯·布拉特(James Bradt)在他的帖子中提到的,Autofac软件包现在已经更新,以解决这个问题,所以任何人在将来会遇到这个问题应该可能会尝试新的包首先:)
正如詹姆斯·布拉特(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);