我正在编写的服务是这样的:
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值是从请求中检索的。我如何注入这个值到构造函数?为简单起见,我们假设类型为bool
如果它在请求中,那么在DI容器调用构造函数时它将不可用。
但是,您可以注入IHttpContextAccessor
并在请求范围内访问的成员中提取头信息。
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
}
}