4

I have a custom authorization filter that has constructor injected dependencies.

public class CustomAuthorizationFilter : IAuthorizationFilter

And a generic attribute that just holds the data.

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class CustomAuthorizeAttribute : FilterAttribute

An approach I "borrowed" from here and I really enjoy the separation. I understand how the filter goes and "gets" the attribute, but I'm missing something with the wire-up.

How do I "bind" the attribute to the filter so that the filter is invoked when the attribute is present? Ninject appears to have a syntax for this. But I haven't figured out an equivalent in Autofac

If this is something I need to setup in the app outside of Autofac, that's fine too.

Thanks! Josh

Community
  • 1
  • 1
Josh
  • 2,740
  • 3
  • 27
  • 41

1 Answers1

1

You could use the same class to be the filter and the attribute. But you can also define another attribute and check if it was defined.

Then you must register your filter/attribute class: inside Global.asax, just like filters.Add(new HandleErrorAttribute());.

Inside the filterMethods (in your case, should be OnAuthorize), you can check if some other attribute IsDefined or if some property was defined.

rcaval
  • 762
  • 5
  • 12
  • So you're saying that you need to register the filter as a global filter, that will execute on every request, and then as part of that execution check to see if another attribute is defined? – Josh Dec 21 '11 at 22:47
  • That's it. From what I've understood. – rcaval Dec 22 '11 at 11:55
  • Okay, I actually tried that, but I wasn't keen on it executing every request. I was able to refactor some things to avoid needing DI, at which point I collapsed the filter and attribute together, but I'd much rather keep them separate. So you're not aware of any autofac syntax similar to the Ninject stuff? – Josh Dec 22 '11 at 14:43
  • I think the filters, even globally configured, will only run for those Controller classes or methods that have been annotated. The default `[Authorize]` attribute works this way. And if you need DI inside your attribute class, you can look [here](http://code.google.com/p/autofac/wiki/Mvc3Integration#Filter_Attribute_Property_Injection) – rcaval Dec 22 '11 at 19:43
  • In my own testing, global filters fire on every request. The `[Authorize]` attribute doesn't work the same way because it is both a filter and an attribute. – Josh Dec 23 '11 at 14:40