asp.net MVC5 - Dependency Injection and AuthorizeAttribute

后端 未结 3 2093
情话喂你
情话喂你 2021-02-13 00:42

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 Depe

3条回答
  •  旧巷少年郎
    2021-02-13 01:26

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

提交回复
热议问题