Castle Windsor

For WebApi Projects

public class ControllersInstaller : IWindsorInstaller
{
    public void Install(
        IWindsorContainer container, 
        IConfigurationStore store)
    {
        container.Register(
            Classes.
                FromThisAssembly().
                BasedOn<IHttpController>(). //Web API
                If(c => c.Name.EndsWith("Controller")).
                LifestyleTransient());
    }
}
public class WindsorConfig
{
    private static IWindsorContainer _container;
    public static IWindsorContainer Container { get { return _container; } }

    public static void RegisterCastleWindsor()
    {
        _container = new WindsorContainer();

        string path = new Uri(
            Path.GetDirectoryName(
                Assembly.GetExecutingAssembly().GetName().CodeBase)).
            AbsolutePath;
        var filter = new AssemblyFilter(path)
            .FilterByAssembly(a => !a.IsDynamic);

        _container.Kernel.Resolver.
            AddSubResolver(new CollectionResolver(_container.Kernel));
        _container.AddFacility<TypedFactoryFacility>();

        _container.AddFacility<LoggingFacility>(f =>
            f.LogUsing(LoggerImplementation.Log4net));

        _container.Install(FromAssembly.InDirectory(filter));

        GlobalConfiguration.Configuration.Services.Replace(
            typeof(IHttpControllerActivator),
            new WindsorWebApiControllerActivator(_container));
    }
}
public class WindsorWebApiControllerActivator : IHttpControllerActivator
{
    private readonly IWindsorContainer _container;

    public WindsorWebApiControllerActivator(IWindsorContainer container)
    {
        _container = container;
    }

    public IHttpController Create(
        HttpRequestMessage request,
        HttpControllerDescriptor controllerDescriptor,
        Type controllerType)
    {
        var controller =
            (IHttpController)this._container.Resolve(controllerType);

        request.RegisterForDispose(
            new Release(
                () => this._container.Release(controller)));

        return controller;
    }

    private class Release : IDisposable
    {
        private readonly Action _release;

        public Release(Action release)
        {
            _release = release;
        }

        public void Dispose()
        {
            _release();
        }
    }
}
public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        WindsorConfig.RegisterCastleWindsor();
        ...
    }
    ...
}

Last modified on: January 11, 2017