如何将值插入从授权获得的构造函数 header

How to insert value into constructor that is obtained from authorization header

我正在编写的服务如下所示:

services.AddScoped<a,b>();
...
public interface a

public class b:a
{
   private readonly someDB db;
   public b(someDB db)
   {
      this.db = db;
   }
}

我要实现的目标如下:


public class b:a
{
   private readonly someDB db;
   private readonly type t;
   public b(someDB db, type t)
   {
      this.db = db;
      this.t= t;
   }
}

问题是从请求中检索了 someType 值。我如何将此值注入构造函数? 为了简单起见,让我们考虑 typebool

如果它在请求中,那么在 DI 容器调用构造函数时它将不可用。

但是,您可以在请求范围内访问的成员中注入 IHttpContextAccessor 并提取 header 信息。

public class b : a {
    private readonly someDB db;
    private readonly IHttpContextAccessor accessor;

    public b(someDB db, IHttpContextAccessor accessor) {
        this.db = db;
        this.accessor = accessor;
    }

    public void SomeMemberThatUsesT() {
        var request = accessor.HttpContext.Request;
        //extract desired header data
    }
}