自定义过滤器属性注入依赖

jas*_*koh 7 c# dependency-injection autofac asp.net-web-api

我正在使用ASP.NET Web API,我需要获得授权,因此我创建了自定义授权属性

public class CustomAuthorizationAttribute : AuthorizeAttribute
Run Code Online (Sandbox Code Playgroud)

为了在构造函数中注入依赖项,我有以下内容:

        public CustomAuthorizationAttribute(IAccountBL accountBl)
    {
        _accountBL = accountBl;
    }
Run Code Online (Sandbox Code Playgroud)

IAccountBL我的方法,它与用户是否被授权作出要求数据库检查交互.在内部成员API控制器中,我注册了该属性

    [CustomAuthorization]
public class MemberController : ApiController
Run Code Online (Sandbox Code Playgroud)

但我得到以下错误

Project.Account.AccountBL'不包含带0个参数的构造函数

如果我注册就好

[CustomAuthorization(IAccountBL)]
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

谢谢

Dar*_*rov 10

动作过滤器只是属性.您无法控制CLR实例化这些属性的时间.一种可能性是编写标记属性:

public class CustomAuthorizationAttribute : Attribute { }
Run Code Online (Sandbox Code Playgroud)

然后是实际的动作过滤器:

public class CustomAuthorizationFilter : ActionFilterAttribute
{
    private readonly IAccountBL accountBL;
    public CustomAuthorizationFilter(IAccountBL accountBL)
    {
        this.accountBL = accountBL;
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<CustomAuthorizationAttribute>().Any() || 
            actionContext.ActionDescriptor.GetCustomAttributes<CustomAuthorizationAttribute>().Any())
        {
            // here you know that the controller or action is decorated 
            // with the marker attribute so that you could put your code
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后将其注册为全局动作过滤器:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...

        IAccountBL accountBL = ...
        config.Filters.Add(new CustomAuthorizationFilter(accountBL));
    }
}
Run Code Online (Sandbox Code Playgroud)

最后你可以使用marker属性:

[CustomAuthorization]
public class MemberController : ApiController
{
    ...
}
Run Code Online (Sandbox Code Playgroud)


Ser*_*pov 8

您可以使用GetDependencyScope类的扩展方法在过滤器中获得依赖关系HttpRequestMessage.它不是依赖注入的规范方式,但可以用作解决方法.一个基本示例可能如下所示:

    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var dependencyScope = context.Request.GetDependencyScope();
        var dependency = dependencyScope.GetService(typeof (MyDependencyType));
        //use your dependency here
    }
Run Code Online (Sandbox Code Playgroud)

此方法可与构造函数注入一起使用,以简化单元测试:

public class MyAuthenticationFilter : Attribute, IAuthenticationFilter
{
    private Func<HttpRequestMessage, MyDependencyType> _dependencyFactory;

    public MyAuthenticationFilter() :
        this(request => (MyDependencyType)request.GetDependencyScope().GetService(typeof(MyDependencyType)))
    {
    }

    public MyAuthenticationFilter(Func<HttpRequestMessage, MyDependencyType> dependencyFactory)
    {
        _dependencyFactory = dependencyFactory;
    }

    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var dependencyScope = context.Request.GetDependencyScope();
        var dependency = dependencyFactory.Invoke(context.Request);
        //use your dependency here
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public bool AllowMultiple { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)


jas*_*koh 2

如果有人发现类似的问题,我将如何解决它。

我的自定义过滤器继承了IAutofacAuthorizationFilter. 除此之外,您还可以继承IAutofacExceptionFilterIAutofacActionFilter。在我的 DI 容器内,我为每个我想使用的控制器注册了这个过滤器,如下所示

        builder.Register(c => new CustomAuthorizationAttribute(c.Resolve<IAccountBL>()))
               .AsWebApiAuthorizationFilterFor<MemberController>()
               .InstancePerApiRequest();
Run Code Online (Sandbox Code Playgroud)