ASP.NET Core 中的需求處理常式中的相依性插入Dependency injection in requirement handlers in ASP.NET Core

使用相依性插入進行設定時,必須在服務集合中註冊授權處理常式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 resolves and injects that into the constructor.

例如,使用 ASP。NET 的記錄基礎結構,插入 ILoggerFactory 處理常式中。For example, to use ASP.NET's logging infrastructure, inject ILoggerFactory into the handler. 這類處理常式可能看起來像下列程式碼:Such a handler might look like the following code:

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;

先前的處理常式可以在任何 服務存留期註冊。The preceding handler can be registered with any service lifetime. 下列程式碼會使用 AddSingleton 來註冊先前的處理常式:The following code uses AddSingleton to register the preceding handler:

services.AddSingleton<IAuthorizationHandler, LoggingAuthorizationHandler>();

當應用程式啟動時,會建立處理常式的實例,而 DI 會將註冊的 ILoggerFactory 插入至函式。An instance of the handler is created when the app starts, and DI injects the registered ILoggerFactory into the constructor.


使用 Entity Framework 的處理常式不應該註冊為 singleton。Handlers that use Entity Framework shouldn't be registered as singletons.