Skip to content

Instantly share code, notes, and snippets.

@mahizsas
Forked from iamkoch/DependencyInjection.cs
Created April 19, 2013 13:04
Show Gist options
  • Select an option

  • Save mahizsas/5420221 to your computer and use it in GitHub Desktop.

Select an option

Save mahizsas/5420221 to your computer and use it in GitHub Desktop.
How to Inject deps in controllers with Castle
using System;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;
using WednesdayFootball.Factory;
[assembly: WebActivator.PreApplicationStartMethod(typeof(WednesdayFootball.AppStart.DependencyInjection), "BootstrapContainer")]
namespace WednesdayFootball.AppStart
{
public static class DependencyInjection
{
private static void BootstrapContainer()
{
var container = new WindsorContainer().Install(FromAssembly.This());
var controllerFactory = new WindsorControllerFactory(container.Kernel);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
RegisterTypes(container);
}
private static void RegisterTypes(IWindsorContainer container)
{
container
.Register(AllTypes
.FromAssemblyInDirectory(new AssemblyFilter(AssemblyDirectory))
.Pick()
.If(x => x.IsPublic)
.If(x => x.GetInterfaces().Length > 0)
.WithService
.FirstInterface()
.LifestyleTransient());
}
static public string AssemblyDirectory
{
get
{
var codeBase = Assembly.GetExecutingAssembly().CodeBase;
var uri = new UriBuilder(codeBase);
var path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment