I have asp.net mvc controller and apicontroller. I trying to use ninject for controller and for apicontroller. And ninject works for controller but doesn't work for 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));
}
when I try to call /api/webapi is requires a default constructor, if I make a default constructor is not created new instance of a IReservationRepository. Regular MVC controller work correctly. How to make them work together?
There is a different Nuget package for web API.
See this
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.