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
答案 0 :(得分: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.