AspNetCore.Docs/aspnetcore/security/authorization/dependencyinjection.md

2.0 KiB

title author description keywords ms.author manager ms.date ms.topic ms.assetid ms.technology ms.prod uid
Dependency Injection in requirement handlers | Microsoft Docs rick-anderson ASP.NET Core, riande wpickett 10/14/2016 article 5fb6625c-173a-4feb-8380-73c9844dc23c aspnet asp.net-core security/authorization/dependencyinjection

Dependency Injection in requirement handlers

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:

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.