2016-10-29 01:35:15 +08:00
---
2018-03-20 07:40:34 +08:00
title: Dependency injection in requirement handlers in ASP.NET Core
2016-10-29 01:35:15 +08:00
author: rick-anderson
2018-03-20 07:40:34 +08:00
description: Learn how to inject authorization requirement handlers into an ASP.NET Core app using dependency injection.
2018-01-29 23:21:31 +08:00
ms.author: riande
2016-10-29 01:35:15 +08:00
ms.date: 10/14/2016
uid: security/authorization/dependencyinjection
---
2018-03-20 07:40:34 +08:00
# Dependency injection in requirement handlers in ASP.NET Core
2016-10-29 01:35:15 +08:00
2017-10-14 04:50:30 +08:00
< a name = "security-authorization-di" > < / a >
2016-10-29 01:35:15 +08:00
2018-03-19 10:25:14 +08:00
[Authorization handlers must be registered ](xref:security/authorization/policies#handler-registration ) in the service collection during configuration (using [dependency injection ](xref:fundamentals/dependency-injection#fundamentals-dependency-injection )).
2016-10-29 01:35:15 +08:00
2017-11-02 03:34:09 +08:00
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.
2016-10-29 01:35:15 +08:00
2017-08-22 23:48:24 +08:00
For example, if you wanted to use ASP.NET's logging infrastructure you would want to inject `ILoggerFactory` into your handler. Such a handler might look like:
2016-10-29 01:35:15 +08:00
2016-11-18 13:03:07 +08:00
```csharp
2016-10-29 01:35:15 +08:00
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;
}
}
2016-11-18 13:03:07 +08:00
```
2016-10-29 01:35:15 +08:00
You would register the handler with `services.AddSingleton()` :
2016-11-18 13:03:07 +08:00
```csharp
2016-10-29 01:35:15 +08:00
services.AddSingleton< IAuthorizationHandler , LoggingAuthorizationHandler > ();
2017-11-02 03:34:09 +08:00
```
2016-10-29 01:35:15 +08:00
2016-11-08 01:58:40 +08:00
An instance of the handler will be created when your application starts, and DI will inject the registered `ILoggerFactory` into your constructor.
2016-10-29 01:35:15 +08:00
> [!NOTE]
> Handlers that use Entity Framework shouldn't be registered as singletons.