-
Notifications
You must be signed in to change notification settings - Fork 17
Action filters registration
hazzik edited this page Apr 14, 2012
·
4 revisions
One interesting side of MvcExtensions is dynamic action filters (IMvcFilter
) registration for MVC controllers. This approach allows you to use filters as regular classes (not as attributes). In that case you will be able to inject your dependencies via constructor. To register filters you need to inherit from abstract class ConfigureFiltersBase
:
public class ConfigureFilters : ConfigureFiltersBase
{
public ConfigureFilters(IFilterRegistry registry) : base(registry) { }
protected override void Configure()
{
Registry.Register<ProductController, PopulateCategories, PopulateSuppliers>(c => c.Create())
.Register<ProductController, PopulateCategories, PopulateSuppliers>(c => c.Edit(0));
}
}
Register with Boootstrapper
:
//Global.asax.cs
public class MvcApplication : MvcExtensions.WindsorMvcApplication
{
public MvcApplication()
{
Bootstrapper.BootstrapperTasks
// ....
.Include<ConfigureFilters>();
}
}
As you can see, we register 2 action filters PopulateCategories
and PopulateSuppliers
for actions Create
and Edit
of ProductController
.
Example of PopulateCategories
class:
public class PopulateCategories : IMvcFilter, IActionFilter
{
private readonly IRepository<Category> repository;
public PopulateCategories(IRepository<Category> repository)
{
this.repository = repository;
}
public bool AllowMultiple { get { return false; } }
public int Order { get; set; }
public void OnActionExecuting(ActionExecutingContext filterContext) { }
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
ProductEditModel editModel = filterContext.Controller.ViewData.Model as ProductEditModel;
if (editModel != null)
{
var categories = new SelectList(repository.All(), "Id", "Name", editModel.Category);
filterContext.Controller.ViewData["categories"] = categories;
}
}
}
Read more http://weblogs.asp.net/rashid/archive/2010/05/27/mvcextensions-actionfilter.aspx