Search code examples
c#asp.net-web-apiowincastle-windsorself-hosting

castle windsor exception when using in selfhosted web api


I'm using Castle Windsor in self hosted Web Api( with OwinSelfHost ), but when I call for example Get method of the controller(it simply return a string), I face the following exception in the GetService method of the WindsorDependencyScope class (implementing IDependencyScope ) :

Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule To fix this add to the section on your web.config. If you plan running on IIS in Integrated Pipeline mode, you also need to add the module to the section under . Alternatively make sure you have Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 assembly in your GAC (it is installed by ASP.NET MVC3 or WebMatrix) and Windsor will be able to register the module automatically without having to add anything to the config file.

Any solution?


Solution

  • I could find the problem. In ControllerInstaller class ,LifestylePerWebRequest lifestyle was used that caused the problem. I don't know the exact technical reason, but when using Windsor castle in composition of "Web Api 2 + self hosted with Owin ", we should use LifestyleScoped instead of LifestylePerWebRequest .Here is the Installer code( the correct one): public class ControllerInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Classes.FromThisAssembly() .Pick().If(t => t.Name.EndsWith("Controller")) .Configure(configurer => configurer.Named(configurer.Implementation.Name)) //.LifestylePerWebRequest() //---this caused the bug .LifestyleScoped() //the correct one ); } }