Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, there are downsides, as there are <a href="https://stackoverflow.com/questions/5653783/is-idependencyresolver-an-anti-pattern/5654204#5654204">lots of issues with IDependencyResolver</a> itself, and to those you can add the use of a <a href="https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons">Singleton</a> Service Locator, as well as <a href="https://stackoverflow.com/questions/7099406/what-is-the-real-difference-between-bastard-injection-and-poor-mans-injection">Bastard Injection</a>.</p> <p>A better option is to implement the filter as a normal class into which you can inject whichever services you'd like:</p> <pre><code>public class MyActionFilter : IActionFilter { private readonly IMyService myService; public MyActionFilter(IMyService myService) { this.myService = myService; } public void OnActionExecuting(ActionExecutingContext filterContext) { if(this.ApplyBehavior(filterContext)) this.myService.DoSomething(); } public void OnActionExecuted(ActionExecutedContext filterContext) { if(this.ApplyBehavior(filterContext)) this.myService.DoSomething(); } private bool ApplyBehavior(ActionExecutingContext filterContext) { // Look for a marker attribute in the filterContext or use some other rule // to determine whether or not to apply the behavior. } private bool ApplyBehavior(ActionExecutedContext filterContext) { // Same as above } } </code></pre> <p>Notice how the filter examines the filterContext to determine whether or not the behavior should be applied.</p> <p>This means that you can still use attributes to control whether or not the filter should be applied:</p> <pre><code>public class MyActionFilterAttribute : Attribute { } </code></pre> <p>However, now that attribute is completely inert.</p> <p>The filter can be composed with the required dependency and added to the global filters in global.asax:</p> <pre><code>GlobalFilters.Filters.Add(new MyActionFilter(new MyService())); </code></pre> <hr> <p>For a more detailed example of this technique, although applied to ASP.NET Web API instead of MVC, see this article: <a href="http://blog.ploeh.dk/2014/06/13/passive-attributes" rel="noreferrer">http://blog.ploeh.dk/2014/06/13/passive-attributes</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload