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

时间:2013-08-23 15:25:26

标签: c# asp.net-web-api dependency-injection autofac

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

public class CustomAuthorizationAttribute : AuthorizeAttribute

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

        public CustomAuthorizationAttribute(IAccountBL accountBl)
    {
        _accountBL = accountBl;
    }

IAccountBL中我有一个与数据库检查交互的方法,如果用户有权发出请求。 在Member API控制器中,我注册了该属性

    [CustomAuthorization]
public class MemberController : ApiController

但我得到以下错误

  

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

如果我将其注册为

[CustomAuthorization(IAccountBL)]

enter image description here

谢谢

4 个答案:

答案 0 :(得分:9)

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

public class CustomAuthorizationAttribute : Attribute { }

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

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

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

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

        IAccountBL accountBL = ...
        config.Filters.Add(new CustomAuthorizationFilter(accountBL));
    }
}

最后你可以使用marker属性:

[CustomAuthorization]
public class MemberController : ApiController
{
    ...
}

答案 1 :(得分:7)

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

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

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

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

答案 2 :(得分:2)

如果有人发现类似的问题,我可以设法解决它。

我的自定义过滤器会继承IAutofacAuthorizationFilter。除此之外,您还可以继承IAutofacExceptionFilterIAutofacActionFilter。 在我的DI容器里面,我为每个想要使用的控制器注册了这个过滤器,就像这个

        builder.Register(c => new CustomAuthorizationAttribute(c.Resolve<IAccountBL>()))
               .AsWebApiAuthorizationFilterFor<MemberController>()
               .InstancePerApiRequest();

答案 3 :(得分:0)

如果您使用任何容器在应用程序上注册了服务,则很容易从范围内的任何位置获取服务实例。只需按照以下代码获得服务即可。

var myService = DependencyResolver.Current.GetService(typeof(IMyService)) as IMyService;

请确保文件中包含System.Web.Mvc

编码愉快!