在.NET Core中添加自定义BasicAuthenticationHandler-问题将必要的服务注入处理程序

我必须添加我们的自定义基本身份验证处理程序,但是我们的实现需要向其传递参数。我无法使用DI来实现。这是代码的一部分:

    // Part of ConfigureServices in Startup.cs
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        // Some DIs in ConfigureService
        services.AddTransient<ICustomService,CustomService>(); //this should be passed later to handler
        services.AddHttpContextaccessor();
        ...
        // Adding authentication in ConfigureServices
        services.AddAuthentication("Basic")
            .AddScheme<CustomBasicAuthenticationOptions,CustomBasicAuthenticationHandler>(
            "Basic",options => new CustomBasicAuthenticationOptions()
            {
                CustomService = ??? // HOW OT GET CustomService: ICustomService from Container here?
            });
      ...
   }

   // CustomBasicAuthenticationOptions
   public class CustomBasicAuthenticationOptions : AuthenticationSchemeOptions
   {
       public CustomBasicAuthenticationOptions();
       public static string AuthenticationScheme { get; }
       public ICustomService CustomService { get; set; }  //THIS SHOULD BE INJECTED HERE during AddAuthentication?! How?
       ...
   }

   // CustomService and its constructor of 
   public class CustomService : ICustomService 
   {
       public CustomService(IHttpContextaccessor httpContextaccessor) {
          ...
       }
   }
dizihenmang1 回答:在.NET Core中添加自定义BasicAuthenticationHandler-问题将必要的服务注入处理程序

您在原始示例中发表的评论显示了实际上取决于服务的内容

  

//应该稍后传递给处理程序

通过构造函数注入将服务作为显式依赖项移至处理程序。

$keyVaultName = "KEYVAULT_NAME_HERE"
$keyVault = Get-AzKeyVault -VaultName $keyVaultName
$accessPolicies = $keyVault.AccessPolicies

# Logging the amount of the items
Write-Host "$keyVault.AccessPolicies.Count"

并重构注册

public class CustomBasicAuthenticationHandler : AuthenticationHandler<CustomBasicAuthenticationOptions> {
    private readonly ICustomService customService;

    public CustomBasicAuthenticationHandler(
        ICustomService customService,//<-- NOTE
        IOptionsMonitor<BasicAuthenticationOptions> options,ILoggerFactory logger,UrlEncoder encoder,ISystemClock clock
    )
    : base(options,logger,encoder,clock) {
        this.customService = customService;
    }

    //...
}
本文链接:https://www.f2er.com/3145742.html

大家都在问