Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter constructor injection using Ninject

I am trying to find a way to use Ninject to inject constructor dependencies into filters. I am finding many articles describing property injection which is now advised against, but the remainder of articles involve complex setups with factories, locators, global wrappers or stub attributes.

With MVC allowing you to override almost any part of it's operation I would have thought it would be simply a case of creating your own filter provider in a similar fashion to how you create your own dependency resolver.

What is the now correct way to allow injection, or does it become easier if you use certain types of filters vs others?

 public class UserValidationAttribute : ActionFilterAttribute
 {
    private IRepository repository;

    public UserValidationAttribute(IRepository repository)
    {
        this.repository = repository;
    }
}
like image 346
John Freebs Avatar asked Sep 25 '13 20:09

John Freebs


2 Answers

There is a way to use constructor injection.

First you replace your attribute with an 'empty' one which you will just use as a marker

public class UserValidationAttribute : Attribute { }

Then you create a filter class as an IActionFilter.

public class UserValidationFilter : IActionFilter
{
    private readonly IRepository repository;

    public UserValidationFilter(IRepository repository)
    {
        this.repository = repository;
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //do something
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //do something
    }      
}

Then you can register it with something like

private static void RegisterServices(IKernel kernel)
{
    kernel.BindFilter<UserValidationFilter>(FilterScope.Action, 0)
        .WhenActionMethodHas<UserValidationAttribute>();
}

If your attribute itself has constructor parameters, you can pass them in like

kernel.BindFilter<UserValidationFilter>(FilterScope.Action, 0)
    .WhenActionMethodHas<UserValidationAttribute>();
    .WithConstructorArgumentFromActionAttribute<UserValidationAttribute>("myParameter", attr => attr.MyParameter);

The BindFilter syntax is part of Ninject.Web.Mvc.FilterBindingSyntax.

like image 85
shamp00 Avatar answered Oct 19 '22 11:10

shamp00


Assuming that the attribute is to be a part of the metadata, which means that it should be instantiated at the compile time, it is not possible to have a repository injected into an attribute by any ioc container. Containers operate in run time.

like image 27
Wiktor Zychla Avatar answered Oct 19 '22 12:10

Wiktor Zychla