在.net核心中使用构造函数参数进行依赖注入

Sta*_*tan 11 c# dependency-injection .net-core asp.net-core

我看到了很多关于如何在.NET Core中使用DI的代码示例,但是没有一个使用构造函数参数.

例如:

  • 创建授权服务
  • 在构造函数中注入当前HTTP标头(X-Api-Key)
  • 在实施中检查我是否有权访问

在这里,我不仅需要在我的DI上使用DI,IAuthorizationService还需要在构造函数中注入令牌.我知道如何在Ninject中完成它,但是没有.NET Core DI的经验.

以下是我的例子.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddEntityFrameworkSqlite();
    services.AddDbContext<MainDbContext>();
    services.AddScoped<IAuthorizationService, AuthorizationService>(); // Inject current HttpContext header value as a constructor?
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*ema 8

我通常通过一个服务来传递这些值,其中数据是在一个中间件中设置的.例如:

可以注入的访问者类:

public class ApiKeyAccessor
{
    public string ApiKey { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

以及在请求开始时设置API密钥的中间件:

public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;

    public ApiKeyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext context, ApiKeyAccessor apiKeyAccessor)
    {
        StringValues key;
        if (context.Request.Headers.TryGetValue("X-Api-Key", out key))
        {
            apiKeyAccessor.ApiKey = key;
            return _next(context);
        }

        // todo: throw exception, etc..
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我们只需要添加ApiKeyAccessor带有作用域生命周期的DI容器并将其添加ApiKeyMiddleware到请求执行管道中,最好尽快.

正确配置后,我们可以ApiKeyAccessor在控制器或服务中注入实例:

public class AuthorizationService
{
   private readonly string _apiKey;

   public AuthorizationService(ApiKeyAccessor apiKeyAccessor)
   {
      _apiKey = apiKeyAccessor.ApiKey;
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这样 - 注入一个类 - 不仅仅是注入一个值,除非这个值像连接字符串一样不变.对于任何给定的DI容器,注入类通常比配置容器以在运行时检索值更容易. (2认同)