1

i have a simple controller where i am using the interfaec like this ,

public class HomeController : Controller
{
    // GET: Home
    private IHotelService hotelService;
    public HomeController(IHotelService _hotelService)
    {
        hotelService = _hotelService;
    }
}

its working fine, but when i use same thing with API controller like

public class RoomController : BaseApiController
{
    private IHotelService hotelService;
    public RoomController(IHotelService _hotelService)
    {
        hotelService = _hotelService;
    }

it gives me error

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • 1
    Please post the error message or log here – Satish Patel Feb 03 '18 at 08:27
  • An error occurred when trying to create a controller of type 'RoomController'. Make sure that the controller has a parameterless public constructor. – Gaurav shukla Feb 03 '18 at 08:29
  • If you read here then you can understand that why that error message is https://msdn.microsoft.com/en-us/library/system.web.http.apicontroller(v=vs.118).aspx Create a constructor without any parameter. – Satish Patel Feb 03 '18 at 08:31
  • How are your injecting the service? What DI framework are you using? –  Feb 03 '18 at 08:36
  • i am using ninject web common for DI , and its working fine with normal web controller but not with api controller that is the actual problem – Gaurav shukla Feb 03 '18 at 09:45
  • Possible duplicate of [MVC5, Web API 2 and Ninject](https://stackoverflow.com/questions/20595472/mvc5-web-api-2-and-ninject) – NightOwl888 Feb 03 '18 at 10:22

1 Answers1

2

As pointed out here (and in several other answers on SO), you have most likely not registered your DI container with Web API. Web API is a separate framework than MVC and therefore it has a separate configuration, including dependency injection.

So, you need to set

GlobalConfiguration.Configuration.DependencyResolver = MyDependencyResovler(container);

at application startup. The details of how to do this depend on what container you are actually using and whether you use a stock dependency resolver or roll your own as shown in Dependency Injection in ASP.NET Web API 2.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212