Can I use Injection / IoC Dependency for ASP.NET MVC FilterAttribute?

I have a simple custom FilterAttribute

one that I use to decorate various ActionMethods

.

eg.

[AcceptVerbs(HttpVerbs.Get)]
[MyCustomFilter]
public ActionResult Bar(...)
{ ... }

      

Now I want to add some entries to this CustomFilter action. So being a good boy, I use DI/IoC

... and as such want to use this template for my custom one FilterAttribute

.

So, if I have the following ...

ILoggingService

      

and want to add this custom one FilterAttribute

. I'm not sure how to do this. For example, I find it easy to do the following ...

public class MyCustomFilterAttribute : FilterAttribute
{
    public MyCustomFilterAttribute(ILoggingService loggingService)
    { ... }
}

      

But compiler errors describing the attribute that decorates mine ActionMethod

(mentioned above ...) requires 1 argument . So I'm just not sure what to do :(

+2


a source to share


3 answers


I have property injection working with Ninject and Ninject.Web.MVC .

As long as you have a factory controller from Ninject.Web.MVC it's pretty simple.

eg.



public class EventExistsAttribute : FilterAttribute, IActionFilter
{
    [Inject]
    public IEventRepository EventRepo { private get; set; }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //Do stuff
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //Do something else if you so wish...
    }
}

      

This has a disadvantage, essentially having a "hidden" dependency, so to speak ... but there is little that can be done about it.

HTHS,
Charles

+3


a source


You need to write your own IActionInvoker and do property injection. Check out this post by Jimmy Bogard for ideas.



+2


a source


Yes it is possible to use dependency injection in FilterAttribute. However, it is not possible to use the constructor injector in the FilterAttribute. This is not a limitation of ASP.NET MVC, it is common to all .NET code, as the values โ€‹โ€‹passed to the constuctor attribute are limited to simple types .

[MyFilter(ILogger logger)] // this will not compile
public ActionResult Index()
{
    return View();
}

      

Thus, a common practice is to make the dependency dependent on your filter, as in @Charlino's example. Then you can use property injection. You can use Ninject to decorate a filter property like @Charlino's example. Or, as @mrydengren suggested, you can do it in a custom subclass of ControllerActionInvoker.

+2


a source







All Articles