我有以下简单的ApiController示例失败。
public class TestAPIController : ApiController
{
public TestAPIController(IKernel kernel) { }
[HttpGet]
public string Test()
{
return "success! " + DateTimeOffset.Now.ToString("F");
}
}
这给了我错误:
加载Ninject组件ICache时出错 没有在内核的组件容器中注册这样的组件。
我安装了Ninject.WebApi.DependencyResolver包但它仍然失败。
这是我在NinjectWebCommon中的CreateKernel类:
private static IKernel CreateKernel()
{
var kernel = new StandardKernel(new VBNinjectModule());
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
//GlobalConfiguration.Configuration.DependencyResolver = new VBNinjectDependencyResolver(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);
return kernel;
}
使用:
Ninject 3.0.1.10
Ninject.MVC3 3.0.0.6
Ninject.Web.Common:3.0.0.7
Ninject.WebApi.DependencyResolver 0.1.4758.24814
提前感谢您的帮助。
干杯!
答案 0 :(得分:0)
您不希望将IKernel注入控制器。相反,您希望注册您的服务,并将该服务注入控制器。
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver =
new NinjectDependencyResolver(kernel);
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IMyService>().To<MyService>().InRequestScope();
}
// Your api controller
public class TestAPIController : ApiController
{
private readonly IMyService _myService ;
public TestAPIController(IMyService myService)
{
_myService = myService;
}
}