Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Umbraco Controllers factories (IObjectFactory is a wrapper for my Windsor container. Use any other IoC technology you want)
public void OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
FilteredControllerFactoriesResolver.Current.InsertType<UmbracoFilteredControllerFactory>(0);
DependencyResolver.SetResolver(new WindsorDependencyResolver(Application.ObjectFactory));
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new WindsorCompositionRoot(Application.ObjectFactory));
}
public class UmbracoFilteredControllerFactory : WindsorControllerFactory, IFilteredControllerFactory
{
public bool CanHandle(RequestContext request)
{
var controllerType = GetControllerType(request, request.RouteData.Values["controller"].ToString());
return ObjectFactory.HasComponent(controllerType);
}
}
// API controller
public class WindsorCompositionRoot : IHttpControllerActivator
{
private readonly IObjectFactory objectFactory;
public WindsorCompositionRoot(IObjectFactory objectFactory)
{
this.objectFactory = objectFactory;
}
public IHttpController Create(HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
var controller = (IHttpController)objectFactory.Resolve(controllerType);
request.RegisterForDispose(new Release(() => objectFactory.Release(controller)));
return controller;
}
private class Release : IDisposable
{
private readonly Action release;
public Release(Action release)
{
this.release = release;
}
public void Dispose()
{
this.release();
}
}
}
// Normal controllers
public class WindsorControllerFactory : DefaultControllerFactory
{
protected readonly IObjectFactory ObjectFactory;
public WindsorControllerFactory()
{
ObjectFactory = Application.ObjectFactory; ;
}
public override void ReleaseController(IController controller)
{
ObjectFactory.Release(controller);
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
if (!requestContext.HttpContext.IsDebuggingEnabled)
{
throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.",
requestContext.HttpContext.Request.Path));
}
return null;
}
return (IController)ObjectFactory.Resolve(controllerType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment