HttpContextAccessor 在.Net 系统中生命周期是singleton。
每一个请求来的时候不是应该New 一个 Context 吗?
它的源码中用到了这个:AsyncLocal<int>
每一个线程会保存它的本地的值。相当于线程的内部变量。
下面代码会打印:
100,100
300,100
100,100
300,100
static void Main(string[] args) { var _threadLocal = 0; AsyncLocal<int> _asyncLocal = new AsyncLocal<int>(); Task.Run(() => { Thread.Sleep(200); _asyncLocal.Value = 100; _threadLocal = 100; while (true) { Thread.Sleep(2000); Console.WriteLine(_asyncLocal.Value+ ","+ _threadLocal); } }); Task.Run(() => { Thread.Sleep(200); _asyncLocal.Value = 300; _threadLocal = 300; while (true) { Thread.Sleep(2000); Console.WriteLine(_asyncLocal.Value+ "," + _threadLocal); } });
}