StefanG
StefanG

Reputation: 1264

Dependency Injection with Api Controller in MVC

I am using Dependency Injection with Castle Windsor in Asp.Net Mvc 4. I use the DefaultControllerFactory pattern and it works for all my Mvc Controllers.

Today I added a new jQuery Control (jqGrid) that uses an ApiController (ItemsApiController) to get the data. The control is in a view of a normal Mvc Controller (ItemsController) and the jqGrid Url property is set to "/api/ItemsApi".

When I start my page, the control is empty and the ItemsApiController is not called. The same code in a dummy project without Dependency Injection works as expected. So I am quite sure the dependency injection is the cause for the problems.

In my DefaultControllerFactory I can see, that the route is not correct parsed:

controller=Items; 
action=api;
id=ItemsApi;

I would expect:

controller=ItemsApi; 
action=GET;

I registered in WebApiConfig my "DefaultApi" (called first) and in RouteConfig my "Default" routes.

When I change the Url property to "./../api/ItemsApi" (what I did not do in my dummy project) the ItemsApiController is called, but not via the Dependency Injection and therefore only with default constructor.

UPDATE: When I implement additionally the IHttpControllerSelector interface, the ItemsApiController is sent to

public HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
  var controllerName = routeData.Values["controller"];
  Resolve<??>
}

but I don't know how to combine the name with Castle Windsor.

Is this the correct way to go? If yes, how can I combine IHttpControllerSelector with Castle?

Upvotes: 0

Views: 532

Answers (1)

StefanG
StefanG

Reputation: 1264

I gave up and used the api controller as composition root.

I think it would be possible in some way to write your own framework, but it would make things too complicated and dependency injection should make my life more easy.

Upvotes: 1

Related Questions