Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFac Injection into attribute

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

like image 341
Jon Gear Avatar asked Sep 16 '15 17:09

Jon Gear


1 Answers

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.

like image 90
Mark Seemann Avatar answered Oct 21 '22 18:10

Mark Seemann