【问题标题】:Add IAuthorization handler to Autofac将 IAuthorization 处理程序添加到 Autofac
【发布时间】:2019-01-21 19:47:15
【问题描述】:

我正在为 ASP.NET Core 创建一些授权策略,显然我已经创建了一些 AuthorizationHandlers。

现在,授权机制要求授权处理程序是可解析的。我使用的是 Autofac 而不是内置机制,所以这是我尝试实现它的方法:

builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
    .AsClosedTypesOf(typeof(AuthorizationHandler<>))
    .As<IAuthorizationHandler>()
    .OnActivating(x => System.Diagnostics.Debug.WriteLine(x.Instance))
    .AutoActivate();

我的理解是:

  1. 我从正在执行的程序集(我的处理程序所在的位置)注册类型
  2. 继承自 AuthorizationHandler
  3. 将它们注册为 IAuthorizationHandler。

为了调试,我添加了 OnActivating 和 AutoActivate 事件。如您所见,当有激活时我正在记录。

但我的日志记录甚至没有执行一次。 Autofac 似乎无法找到我的授权处理程序。如何解决?

【问题讨论】:

    标签: asp.net asp.net-core asp.net-core-2.0 autofac


    【解决方案1】:

    您发布的代码看起来很完美。无论如何,我已经对其进行了测试并按预期为我工作(包括自动激活)。环境:NET Core 2.1,Autofac.Extensions.DependencyInjection 4.2.2。

    我 99.9% 确定问题出在其他地方。我可以想到以下几点:

    • 在执行程序集中没有扩展 AuthorizationHandler 的非抽象类或
    • 更有可能的是,您的 Autofac 容器无法构建。

    你的 Startup.ConfigureServices 方法看起来像这样吗?

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        // standard ASP.NET Core setup like
        services.AddMvc(...)
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
        var builder = new ContainerBuilder();
    
        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            .AsClosedTypesOf(typeof(AuthorizationHandler<>))
            .As<IAuthorizationHandler>()
            .OnActivating(x => System.Diagnostics.Debug.WriteLine(x.Instance))
            .AutoActivate();
    
        builder.Populate(services);
    
        var container = builder.Build();
        return new AutofacServiceProvider(container);
    }
    

    【讨论】:

    • 呃,我真傻。授权处理程序位于不同的程序集中。正如你所说,代码是完美的。
    【解决方案2】:

    我必须有 50 声望才能发表评论,所以我会回答

    @Adam Simon 对 AuthorizationHandlers 的回答是正确的,但它没有正确注册基于资源的资源处理程序。

    您必须使用另一行添加另一个 RegisterAssemblyTypes 调用

    .AsClosedTypesOf(typeof(AuthorizationHandler<,>)) // notice comma in generic type
    

    (注意泛型中的逗号)

    两种 AuthorizationHandlers 的工作版本是:

    builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
        .AsClosedTypesOf(typeof(AuthorizationHandler<>))
        .As<IAuthorizationHandler>()
        .OnActivating(x => System.Diagnostics.Debug.WriteLine(x.Instance))
        .AutoActivate();
    
    builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
        .AsClosedTypesOf(typeof(AuthorizationHandler<,>))
        .As<IAuthorizationHandler>()
        .OnActivating(x => System.Diagnostics.Debug.WriteLine(x.Instance))
        .AutoActivate();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2018-08-24
      • 2011-07-03
      • 1970-01-01
      • 2013-05-06
      • 2012-05-11
      相关资源
      最近更新 更多