Example
public interface ISingleton : IDisposable { }
public class TransientDependency { }
public class Singleton : ISingleton
{
public void Dispose() { }
}
public class CompositionRoot : IDisposable, IControllerFactory
{
private readonly ISingleton _singleton;
// pass in any true singletons i.e. cross application instance singletons
public CompositionRoot()
{
// intitialise any application instance singletons
_singleton = new Singleton();
}
public void Dispose()
{
_singleton.Dispose();
}
public IController CreateController(RequestContext requestContext, string controllerName)
{
if (controllerName.ToLower() == "home")
{
return new HomeController(_singleton, new TransientDependency());
}
var argumentException = new ArgumentException(@"Unexpected controller! " + controllerName);
Log.Error("don't know how to instantiate MVC controller: {controllerType}. redirecting to help", controllerName);
throw argumentException; // Alternatively would return some default Page Not Found placeholder controller;
}
public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
{
return SessionStateBehavior.Default;
}
public void ReleaseController(IController controller)
{
// anything to clean up?
}
}
public static class DependencyInjection
{
public static void WireUp()
{
var compositionRoot = new CompositionRoot();
System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(compositionRoot);
}
}