Insert AutoFac into an attribute

Therefore, I need to introduce several different services into the authorization attribute that I use. 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 will be used as follows

 [FeatureAuthorize("Admin")] 

I tried using constructor injection

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

However, this just causes an error when trying

 [FeatureAuthorize("Admin", IConfigurationManager)] 

It seems that this is not so. I assume that I need to register my own authorization attribute with the container so that it starts collecting

+5
source share
1 answer

Instead of trying to use Injection Dependency with attributes (which you cannot do in any reasonable, useful way), create Passive attributes .

In particular, in this case, assuming this is an ASP.NET MVC script, you cannot get an AuthorizeAttribute . Instead, you should force your authorization service to look for your own attribute and implement IAuthorizationFilter . Then add a filter to your application configuration.

More details can be found in this answer: fooobar.com/questions/83819 / ....

+8
source

All Articles