Ninject与asp.net mvc 5控制器和apicontroller

时间:2015-10-31 18:39:01

标签: c# asp.net-mvc asp.net-web-api ninject ninject.web.mvc

我有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控制器正常工作。如何让它们一起工作?

1 个答案:

答案 0 :(得分:0)

Web API有一个不同的Nuget包。

请参阅this