Tuesday, 28 September 2010

IoC and MVC Action Filter Attributes

As I’ve previously mentioned anyone starting out with IoC and ASP.NET MVC quickly encounters problems injecting HttpContext and related classes into controllers, etc.  A similar issue surrounds Action Filter Attributes but is not limited to just HttpContext as objects inheriting from ActionFilterAttribute must contain a “parameter less” default constructor.  Without a “parameter less” constructor these objects can not be created when used to decorate a class or action declaration.  Also, the MVC engine is responsible for the creation of the attributes when they are decorating class/action declarations, completely by-passing the IoC container and any hope of using property injectors. 

The only way to gain access to the IoC container is to make sure that it is available through a static public object (such as global.asax) and reference the container directly in the filter constructor.  This is not ideal, but checking other articles on the web, there does not appear to be any better solution available.   It is also a good idea to provide a constructor that can be used for DI for Unit Testing the action filter in isolation.

It is also worth noting that if you control the creation/injection of HttpContextBase within your IoC container, then the version of HttpContext that is held in filterContext in “OnActionExecuting” will be a different instance to that supplied in the IoC container.  In this example I attempted to use filerContext.HttpContext.Response to write cookie values that were checked later.  This code failed because the Action Filter and IoC container worked against separate instances – I would write the cookie, but the subsequent read would not find it.  Also the Response object in the filter would always record that the client was not connected.

public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
// As you can't inject directly into an action filter, this allows full control for
// unit testing, whilst providing auto creation for actual code.
private IAuthenticationCookie _authenticationCookie;

public RequiresAuthenticationAttribute()
{
_authenticationCookie = MvcApplication.WindsorContainer.Resolve<IAuthenticationCookie>();
}

public RequiresAuthenticationAttribute(IAuthenticationCookie authenticationCookie)
{
if (authenticationCookie == null) throw new ArgumentNullException("authenticationCookie");
_authenticationCookie = authenticationCookie;
}

public string Controller { get; set; }
public string Action { get; set; }

public override void OnActionExecuting(ActionExecutingContext filterContext)
{



del.icio.us Tags: ,,

No comments:

Post a Comment