I have a situation where I need to inject some dependencies in a action filter, namely, my custom authorization provider in my custom authorization attribute. I stumbled upo
This is probably a bit much, but one way of avoiding the factory as suggested by David (and making this a little more generic) is to introduce yet another attribute.
[AssociatedFilter(typeof(MyAuthorizationFilter))]
Which you could add to the original attribute as follows.
[AssociatedFilter(typeof(MyAuthorizationFilter))]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : Attribute
{
public string Code { get; set; }
}
The AssociatedFilter Attribute looks like this.
public class AssociatedFilterAttribute : Attribute
{
public AssociatedFilterAttribute(Type filterType)
{
FilterType = filterType;
}
public Type FilterType { get; set; }
}
Then you can retrieve the correct filter by pulling out the FilterType from this attribute.
private object Resolve(Attribute attribute)
{
var filterAttributes = attribute.GetType().GetCustomAttributes(typeof(AssociatedFilterAttribute), false);
var first = (AssociatedFilterAttribute)filterAttributes.FirstOrDefault();
return new Filter(_container.Resolve(first.FilterType), FilterScope.First, null);
}
Currently this is limited to only taking the first AssociatedFilter attribute, theoretically I guess you could add more than one (one attribute kicks off several filters) in which case you'd omit the bit where this grabs the first result.
Obviously we also need to add error handling, e.g. if there is no AssociatedFilterAttribute...