Search code examples
c#asp.net-web-apidependency-injectionautofac

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;
    }

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

    [CustomAuthorization]
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

[CustomAuthorization(IAccountBL)]

enter image description here

Thank you


Solution

  • 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>()))
                   .AsWebApiAuthorizationFilterFor<MemberController>()
                   .InstancePerApiRequest();