我正在用 MVC4 连接 Ninject 并让它工作到它试图真正解决依赖关系的地步。但是,我收到以下异常:
找不到方法:“System.Web.Http.Services.DependencyResolver System.Web.Http.HttpConfiguration.get_ServiceResolver()”。
有人遇到过这个并有解决方法吗?
我正在用 MVC4 连接 Ninject 并让它工作到它试图真正解决依赖关系的地步。但是,我收到以下异常:
找不到方法:“System.Web.Http.Services.DependencyResolver System.Web.Http.HttpConfiguration.get_ServiceResolver()”。
有人遇到过这个并有解决方法吗?
GlobalConfiguration.Configuration.ServiceResolver
GlobalConfiguration.Configuration.DependencyResolver
在 RC 中被替换为。所以我猜你使用的 Ninject 包根本不是为 RC 设计的。这是重大变化之一。
下面是使 Ninject 与 ASP.NET MVC 4 Web API RC 一起工作的步骤:
声明一个接口:
public interface IFoo
{
string GetBar();
}
然后是一个实现:
public class Foo : IFoo
{
public string GetBar()
{
return "the bar";
}
}
然后添加一个 API 控制器:
public class ValuesController : ApiController
{
private readonly IFoo _foo;
public ValuesController(IFoo foo)
{
_foo = foo;
}
public string Get()
{
return _foo.GetBar();
}
}
安装Ninject.Mvc3
NuGet 包 ( Install-Package Ninject.Mvc3
)
定义一个自定义 API 依赖解析器,如下图所示:
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public void Dispose()
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
disposable.Dispose();
resolver = null;
}
public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.GetAll(serviceType);
}
}
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}
在~/App_Start/NinjectWebCommon.cs/CreateKernel
安装 NuGet 时创建的方法中,在行后添加以下RegisterServices(kernel);
行:
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
配置内核:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IFoo>().To<Foo>();
}
点击F5并导航到/api/values
the bar
.显然,当 RC 达到 RTM 时,我希望会有一个Ninject.Mvc4
NuGet 将这 10 个步骤缩短到最多 5 个。