using System;
using System.Web.Mvc;
namespace MvcContrib.Binders
{
///
/// Binder that creates SubControllers that are needed for an action method
///
public class SubControllerBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if(typeof(ISubController).IsAssignableFrom(bindingContext.ModelType))
{
object instance = CreateSubController(bindingContext.ModelType);
if(instance == null)
{
throw new InvalidOperationException(bindingContext.ModelType + " not created properly.");
}
return instance;
}
return base.BindModel(controllerContext, bindingContext);
}
///
/// Creates the subcontroller given its type. Override this method to wire into an IoC container
///
///The type of subcontroller
///an object instance
public virtual object CreateSubController(Type destinationType)
{
return Activator.CreateInstance(destinationType, true);
}
}
}