9

So I have a need for injecting a number of different services into an authorization attribute I'm using. For simplicity I will leave this to show the configuration manager.

public class FeatureAuthorizeAttribute : AuthorizeAttribute
{
    public IConfigurationManager ConfigurationManager;

    private readonly string _feature;
    public FeatureAuthorizeAttribute(string feature)
    {
        _feature = feature;

        var test  = ConfigurationManager.GetCdnPath();
    }
}

Which would be used as follows

[FeatureAuthorize("Admin")]

I have tried to use constructor injection

public FeatureAuthorizeAttribute(string feature, IConfigurationManager configurationManager)
{
   ConfigurationManager = configurationManager;
   _feature = feature
}

However this just causes an error when I attempt

[FeatureAuthorize("Admin", IConfigurationManager)]

Which seems like the wrong way to go about it in the first place. I'm assuming that I need to register my custom authorization attribute with the container to get it to start picking up

Jon Gear
  • 1,008
  • 1
  • 11
  • 22

1 Answers1

12

Instead of trying to use Dependency Injection with attributes (which you can't do in any sane, useful way), create Passive Attributes.

Specifically, in this case, assuming that this is an ASP.NET MVC scenario, you can't derive from AuthorizeAttribute. Instead, you should make your Authorization service look for your custom attribute, and implement IAuthorizationFilter. Then add the filter to your application's configuration.

More details can be found in this answer: https://stackoverflow.com/a/7194467/126014.

Community
  • 1
  • 1
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • 1
    This is exactly what I was looking for! Thank you! Mark you are a gentleman and a scholar. The only piece I'm a little fuzzy on is how I get this custom filter to correlate to my custom attribute – Jon Gear Sep 16 '15 at 18:14
  • 1
    @JonGear If you look at the example given in the [Passive Attributes](http://blog.ploeh.dk/2014/06/13/passive-attributes) article, you'll notice that it starts by looking after the custom attribute in `actionContext.ActionDescriptor`. In MVC, IIRC you can do the same with [ActionExecutingContext](https://msdn.microsoft.com/en-us/library/system.web.mvc.actionexecutingcontext). – Mark Seemann Sep 16 '15 at 19:25