Saturday, 28 November 2015

Configuring Windsor Castle with Web API and MVC

Add below to the Application_Start() in Global.asax.cs
 
WindsorActivationConfig.Setup(GlobalConfiguration.Configuration);
 

public static class WindsorActivationConfig
    {
        public static void Setup(HttpConfiguration config)
        {
            IWindsorContainer container = new WindsorContainer();

            container.Register(Classes.FromThisAssembly().BasedOn().LifestyleTransient());

            config.Services.Replace(typeof(IHttpControllerActivator), new WindsorControllerActivator(container));

           // register your components here now
        }
    }

 
public class WindsorControllerActivator : IHttpControllerActivator
    {
        private readonly IWindsorContainer _container;

        public WindsorControllerActivator(IWindsorContainer container)
        {
            this._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)
            {
                this._release = release;
            } 
            public void Dispose()
            {
                this._release();
            }
        }
    }

  
public abstract class DependenciesInstallerBase
    {
        protected readonly WindsorContainer Container;

        protected DependenciesInstallerBase(WindsorContainer container, bool enableArrayInjection = true)
        {
            Container = container;

            if (enableArrayInjection)
            {
                // enables injection of interface arrays to a registered object
                Container.Kernel.Resolver.AddSubResolver(new CollectionResolver(Container.Kernel));
            }
        }
        
        protected void RegisterAllDefaultInterfacesWithinAssembly()
        {
            // registers objects with their interfaces
            // registers multiple objects for the same interface
            Container.Register(Classes
                .FromAssembly(typeof(T).Assembly)                
                .BasedOn()
                .WithService.AllInterfaces()         
                .LifestyleTransient());            
        }
    }