我有asp.net mvc控制器和apicontroller。我试图使用ninject作为控制器和apicontroller。 ninject适用于控制器,但不适用于apicontroller。
using System.Web.Mvc;
using MvcAPI_demo.Models;
namespace MvcAPI_demo.Controllers
{
public class HomeController : Controller
{
private readonly IReservationRepository _repository;
public HomeController(IReservationRepository repository)
{
_repository = repository;
}
//
// GET: /Home/
public ActionResult Index()
{
return View(_repository.GetAll());
}
}
using System.Collections.Generic;
using System.Web.Http;
using MvcAPI_demo.Models;
namespace MvcAPI_demo.Controllers
{
public class WebApiController : ApiController
{
private readonly IReservationRepository _repository;
public WebApiController()
{
}
public WebApiController(IReservationRepository repository)
{
_repository = repository;
}
public IEnumerable<Reservation> GetAllReservations()
{
return _repository.GetAll();
}
}
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MvcAPI_demo.Models;
using Ninject;
namespace MvcAPI_demo.Infrastructure
{
public class NinjectDependencyResolver : IDependencyResolver
{
private readonly IKernel _kernel;
public NinjectDependencyResolver()
{
}
public NinjectDependencyResolver(IKernel kernel)
{
_kernel = kernel;
AddBinding();
}
private void AddBinding()
{
_kernel.Bind<IReservationRepository>().To<NonPersistReservationRepository>().InSingletonScope();
}
public object GetService(Type serviceType)
{
return _kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _kernel.GetAll(serviceType);
}
}
}
NinjectWebCommon.cs
private static void RegisterServices(IKernel kernel)
{
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
当我尝试调用 / api / webapi 时需要默认构造函数,如果我使默认构造函数没有创建IReservationRepository的新实例。常规MVC控制器正常工作。如何让它们一起工作?