Search code examples
c#asp.net-mvcasp.net-mvc-4asp.net-web-apicastle-windsor

IoC: Castle Windsor and WebAPI


I have an MVC4 site using Castle Windsor that I want to add some WebAPI calls to, so I start digging around a little bit on the interwebs.

Now I don't know the ins and outs of IoC; I followed a tutorial for how to set up Castle Windsor on my project, injecting the IUnitOfWorkFactory and the IApplicationService as public properties in a base controller, and a few other interfaces as needed in the controller constructors. It works swimmingly, so I've never had to do more with it.

Everywhere that I'm reading up on WebAPI, I'm told DI will not work so well using Castle Windsor, talking about problems with the IDependencyResolver and IDependencyScope. There are several workarounds and implementations of how to get around this problem, but what is not clear to me is what exactly the problem is. Code snippets are included, but the assumption is you know what class they belong to, and how they are invoked, which unfortunately I do not. Additionally, all the examples I've seen online refer to an exclusive WebAPI project, and not an MVC4 project with a couple ApiControllers judiciously tossed in. I don't know how, or if, this affects anything.

Why won't what I have working with my standard controllers not work with an API controller? What kind of code acrobatics need to do to get WebAPI calls and standard web calls to work in the same application?


Solution

  • In order to use Windsor with webapi follow http://blog.ploeh.dk/2012/10/03/DependencyInjectioninASP.NETWebAPIwithCastleWindsor/ (BEH: fixed link)

    Read also Castle Windsor/DelegatingHandler/IPrincipal Dependency Injection (DI)/Inversion of Control (IoC) in ASP.NET Web API

    You can use webapi and MVC controllers in the same app (I prefer to keep it separate) but routing and controllers factory are different and you have to set up two different configuration and handle routing overlaps... For MVC & Windsor you can find a great