jasenkoh jasenkoh - 5 months ago 73
C# Question

Custom filter attributes inject dependency

I'musing ASP.NET Web API and I need to have authorization so I've created custom authorization attribute

public class CustomAuthorizationAttribute : AuthorizeAttribute

In order to inject dependency inside constructor I have following :

public CustomAuthorizationAttribute(IAccountBL accountBl)
_accountBL = accountBl;

I have method which interacts with database checking if user is authorized to make request.
Inside Member API controller I've register that attribute

public class MemberController : ApiController

But I get following error

Project.Account.AccountBL' does not contain a constructor that takes 0 arguments

And if I register it like


enter image description here

Thank you

Answer Source

If anyone finds similar issue here's how I manage to solve it.

My custom filter inherits IAutofacAuthorizationFilter. Besides this one you can also inherit IAutofacExceptionFilter and IAutofacActionFilter. And inside my DI container I've register this filter for each controller I want to use like this

        builder.Register(c => new CustomAuthorizationAttribute(c.Resolve<IAccountBL>()))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download