ASP.NET MVC3 + ActionFilterAttribute + Injection?

后端 未结 2 1854
攒了一身酷
攒了一身酷 2020-12-10 15:03

Hey there, I\'ve succesfull been able to use property injection in my FilterAttribute, however I\'m wondering whether its possible to move it into the constructor instead?

2条回答
  •  情深已故
    2020-12-10 15:24

    No, this isn't possible as the parameters for the constructors must be simple types.

    For testing purposes, you could have another constructor (since you shouldn't be using an IoC container with testing):

    public class AuthAttribute : ActionFilterAttribute
    {
        public Roles _authRoles { get; private set; }
    
        [Inject]
        private readonly IAuthorizationService _service;
    
        public AuthAttribute(Roles roles)
        {
            _authRoles = roles;
        }
    
        public AuthAttribute(Roles roles, IAuthorizationService authSvc)
            : this(roles)
        {
            this.service = authSvc;
        }
    
        // ...
    }
    

提交回复
热议问题