Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

490
Views
asp.net MVC5 - Dependency Injection and AuthorizeAttribute

I searched a long time for a solution for my problem. I have a custom AuthorizeAttribute that needs a Dependency to a "Service" that has access to a DbContext. Sadly the Dependency Injection did not work in the custom AuthorizeAttribute and was always null.

I came up with an (for me) acceptable solution. Now I want to know if my solution can cause unforeseen behaviour?

Global.asax.cs

 CustomAuthorizeAttribute.AuthorizeServiceFactory = () => unityContainer.Resolve<AuthorizeService>();

CustomAuthorizeAttribute.cs

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public static Func<AuthorizeService> AuthorizeServiceFactory { get; set; }

        public Privilege Privilege { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool authorized = base.AuthorizeCore(httpContext);
            if (!authorized)
            {
                return false;
            }

            return AuthorizeServiceFactory().AuthorizeCore(httpContext, Privilege);
        }
    }

AuthorizeService.cs

public class AuthorizeService
{
    [Dependency]
    public UserService UserService { private get; set; }

    public bool AuthorizeCore(HttpContextBase httpContext, Privilege privilege)
    {
        ApplicationUser user = UserService.FindByName(httpContext.User.Identity.Name);
        return UserService.UserHasPrivilege(user.Id, privilege.ToString());
    }
}

Is this an acceptable solution? Will I run into nasty problems in the future or is there maybe a better way to use Dependency Injection in a custom AuthorizeAttribute?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

I have a custom AuthorizeAttribute that needs a Dependency to a "Service" that has access to a DbContext. Sadly the Dependency Injection did not work in the custom AuthorizeAttribute and was always null.

An implementation of IControllerFactory in the System.Web.Mvc namespace creates instances your Controllers for web requests. The Controller Factory uses System.Web.Mvc.DependencyResolver to resolve dependencies in each controller.

However, ActionFilters/Attributes in the MVC pipeline are not created from the Controller Factory so dependencies are not resolved using System.Web.Mvc.DependencyResolver. This is why your dependency was always null.

Now, System.Web.Mvc.DependencyResolver is public and static so you can access it yourself.

    public class AuthorizeService : AuthorizeAttribute
    {
        private UserService UserService
        {
            get
            {
                return DependencyResolver.Current.GetService<UserService>();
            }
        }

        public bool AuthorizeCore(HttpContextBase httpContext, Privilege privilege)
        {
            ApplicationUser user = UserService.FindByName(httpContext.User.Identity.Name);
            return UserService.UserHasPrivilege(user.Id, privilege.ToString());
        }
    }

Assuming your UserServicehas a dependency scope of WebRequest, i.e. its lifetime is One Per web request and tied to the lifetime of HttpContext of a web request this will not construct a new UserService if one has been resolved previously or after if this is the first time UserService has been resolved for the given web request.

over 4 years ago · Santiago Trujillo Report

0

In ASP.NET Core you can request services easily as below:

public class CustomAuthAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    public async void OnAuthorization(AuthorizationFilterContext context)
    {
        // var user = context.HttpContext.User;

        // if (!user.Identity.IsAuthenticated)
        // {
        //     context.Result = new UnauthorizedResult();
        //     return;
        // }

        var userService = context.HttpContext.RequestServices.GetService(typeof(UserService)) as UserService;
    }
}
over 4 years ago · Santiago Trujillo Report

0

You can also try this:

ASP.NET Web API and dependencies in request scope

public override void OnAuthorization(HttpActionContext filterContext)
{
    var requestScope = filterContext.Request.GetDependencyScope();
    _userService = requestScope.GetService(typeof(IUserService)) as IUserService;
}

//
// Summary:
//     Retrieves the System.Web.Http.Dependencies.IDependencyScope for the given request
//     or null if not available.
//
// Parameters:
//   request:
//     The HTTP request.
//
// Returns:
//     The System.Web.Http.Dependencies.IDependencyScope for the given request or null
//     if not available.
public static IDependencyScope GetDependencyScope(this HttpRequestMessage request);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!