Using Castle Windsor with WCF Web Api (Preview 6)

I’ve got used to treating everything as a service in recent years, since I started using Castle Windsor. I only ever instantiate my own classes in unit/integration tests these days. My latest project has been to write a RESTful service using preview 6 of the WCF Web Api framework. (Also available via nuget, just add the WebApi.All package and you’re all set). It’s actually quite simple to make the web api use castle windsor.

From my Application_Start() method I call a ConfigureApi(RouteCollection routes) method. This create the config object and then sets up any routes …

private static void ConfigureApi(RouteCollection routes)
    Container = CreateContainer();

    var config = new MyApiConfiguration(Container);


I then set up CreateInstance, ErrorHandlers, and MessageHandlerFactory with anonymous methods which simply call the relevant Resolve methods on my container.

public class MyApiConfiguration : WebApiConfiguration
    public MyApiConfiguration(IWindsorContainer container)
        EnableTestClient = GetSetting("TestClient");
        IncludeExceptionDetail = GetSetting("IncludeExceptionDetail");

        CreateInstance = ((serviceType, context, request) => container.Resolve(serviceType));
        ErrorHandlers = (handlers, endpoint, description) => handlers.Add(container.Resolve<GlobalErrorHandler>());
        MessageHandlerFactory = () => container.ResolveAll<DelegatingHandler>();


    private static bool GetSetting(string settingName)
        bool flag;
        bool.TryParse(ConfigurationManager.AppSettings[settingName] ?? "false", out flag);
        return flag;

And that’s all there is to it. Simple really.

ValidateAllResourceTypes is something I will blog about another time. It uses reflection to register all resource types for validation via data annotations.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s