• Security » Authorization » 要求处理器中的依赖注入


    Dependency Injection in requirement handlers

    30 of 32 people found this helpful

    Authorization handlers must be registered in the service collection during configuration (using dependency injection).

    授权处理器必须在配置期间注册到服务集合中。

    Suppose you had a repository of rules you wanted to evaluate inside an authorization handler and that repository was registered in the service collection. Authorization will resolve and inject that into your constructor.

    假设你有一个存储库的规则,你想在一个授权处理程序中进行检查,并且该库在服务集合中注册。授权将解决并将其注入到您的构造函数中。

    For example, if you wanted to use ASP.NET’s logging infrastructure you would to inject ILoggerFactory into your handler. Such a handler might look like:

    例如,如果你想使用ASP.NET的登陆功能,你将在处理程序中注入IloggerFactory。这样的处理程序可能看起来像:

    public class LoggingAuthorizationHandler : AuthorizationHandler<MyRequirement>
    {
        ILogger _logger;
    
        public LoggingAuthorizationHandler(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger(this.GetType().FullName);
        }
    
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
        {
            _logger.LogInformation("Inside my handler");
            // Check if the requirement is fulfilled.
            return Task.CompletedTask;
        }
    }

    You would register the handler with services.AddSingleton():

    services.AddSingleton<IAuthorizationHandler, LoggingAuthorizationHandler>();

    An instance of the handler will be created when your application starts, and DI will inject the registered ILoggerFactory into your constructor.

    Note

    Handlers that use Entity Framework shouldn’t be registered as singletons.

    使用EF的处理程序不应被注册为单数。

    原文链接

  • 相关阅读:
    C# 多线程Thread.IsBackground=True的作用
    JS 判断用户设备 移动端或桌面端
    VSCode 代码格式化 快捷键
    PHP 根据 IP 获取定位数据
    C# 将文本写入到文件
    C# 读取文件内容
    PHP 美化输出数组
    VSCode 设置 Tab 空格
    custom post types 404 Page Error
    [已解决] wordpress 修改 permalink 后 页面 404 问题
  • 原文地址:https://www.cnblogs.com/jqdy/p/5993946.html
Copyright © 2020-2023  润新知