我刚刚安装了 mvc4 rc 更新,我正在尝试构建一个 api 应用程序,但运气不佳。
我正在使用 ninject 但无法加载我的控制器。我不断收到错误
类型 'Api.Controllers.ConsumerController' 没有默认构造函数
我对 mvc 和使用注入非常陌生,所以请多多包涵。
我没有对通过 nuget 创建的默认绑定做任何特别的事情
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IConsumerRepository>().To<ConsumerRepository>();
}
}
我的控制器看起来像
private readonly IConsumerRepository _repository;
public ConsumerController(IConsumerRepository repository)
{
_repository = repository;
}
[HttpGet]
public IQueryable<Consumer> Get(Guid id)
{
return _repository.Get(id).AsQueryable();
}
我需要做什么才能让 api 控制器与 ninject 一起工作?
对不起,如果这是简单的东西
但是,在将 webcommon.cs 更改为此之后,我尝试了您的建议 Michael
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;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IConsumerRepository>().To<ConsumerRepository>();
}
我收到错误时
var kernel = new StandardKernel();
叫做
来自程序集“Ninject.Web.WebApi,版本=3.0.0.0,文化=中性,PublicKeyToken=c7192dc5380945e7”的“Ninject.Web.WebApi.Filter.DefaultFilterProvider”类型中的方法“GetFilters”没有实现。
我错过了什么?