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的处理程序不应被注册为单数。

原文链接

原文地址:https://www.cnblogs.com/jqdy/p/5993946.html