Skip to content

Instantly share code, notes, and snippets.

@uhaciogullari
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uhaciogullari/fd8ce59e83b098f01053 to your computer and use it in GitHub Desktop.
Save uhaciogullari/fd8ce59e83b098f01053 to your computer and use it in GitHub Desktop.
ASP.NET MVC - Castle Windsor
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
WindsorBootstrapper.CreateBootstrapContainer();
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
protected void Application_End()
{
WindsorBootstrapper.DisposeContainer();
}
}
public class WindsorBootstrapper
{
private static IWindsorContainer __container;
public static void CreateBootstrapContainer()
{
WindsorContainer windsorContainer = new WindsorContainer();
windsorContainer.Kernel.Resolver.AddSubResolver(new ArrayResolver(windsorContainer.Kernel));
//windsorContainer.Install(new WebsiteInstaller());
__container = windsorContainer;
WindsorControllerFactory controllerFactory = new WindsorControllerFactory(__container.Kernel);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
DependencyResolver.SetResolver(new WindsorDependencyResolver(__container.Kernel));
}
public static void DisposeContainer()
{
__container.Dispose();
}
}
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IKernel _kernel;
public WindsorControllerFactory(IKernel kernel)
{
_kernel = kernel;
}
public override void ReleaseController(IController controller)
{
_kernel.ReleaseComponent(controller);
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
}
return (IController)_kernel.Resolve(controllerType);
}
}
public class WindsorDependencyResolver : System.Web.Mvc.IDependencyResolver
{
private readonly IKernel _kernel;
public WindsorDependencyResolver(IKernel kernel)
{
_kernel = kernel;
}
public object GetService(Type serviceType)
{
return _kernel.HasComponent(serviceType) ? _kernel.Resolve(serviceType) : null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _kernel.HasComponent(serviceType) ? _kernel.ResolveAll(serviceType).Cast<object>() : new object[] { };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment