public void ThreadAndGlobalServiceTest() { BaseTest.RegisterServiceCollection(); BaseTest.RegisterServiceStart(true); SenparcDI.GlobalServiceCollection.AddScoped <SenparcSetting>(); SenparcDI.GlobalIServiceProvider = null; //测试跨线程唯一 var s = SenparcDI.GetService <SenparcSetting>(true); Console.WriteLine($"s:{s.GetHashCode()}"); var threadsCount = 10; Console.WriteLine("======= 开始全局唯一测试 ======="); var finishedThread = 0; for (int i = 0; i < threadsCount; i++) { var index = i; var thread = new Thread(() => { var s1 = SenparcDI.GetService <SenparcSetting>(true); var s2 = SenparcDI.GetService <SenparcSetting>(true); Console.WriteLine("ServiceProcider:" + SenparcDI.GlobalIServiceProvider?.GetHashCode()); Console.WriteLine($"{index}:{s1.GetHashCode()}"); Console.WriteLine($"{index}:{s2.GetHashCode()}"); Assert.AreEqual(s1.GetHashCode(), s2.GetHashCode()); finishedThread++; }); thread.Start(); } while (finishedThread != threadsCount) { } //所有HashCode相同 //测试通线程唯一 Console.WriteLine("======= 开始线程内唯一测试 ======="); finishedThread = 0; for (int i = 0; i < threadsCount; i++) { var thread = new Thread(() => { var index = i; Console.WriteLine($"-------{index}----------"); var threadScope = Thread.GetData(Thread.GetNamedDataSlot(CO2NET.SenparcDI.SENPARC_DI_THREAD_SERVICE_Scope)) as IServiceScope; Console.WriteLine("ServiceScope:" + threadScope?.GetHashCode()); Console.WriteLine("ServiceProcider:" + threadScope?.ServiceProvider.GetHashCode()); var s1 = SenparcDI.GetService <SenparcSetting>(false); var s2 = SenparcDI.GetService <SenparcSetting>(false); Console.WriteLine($"{index}:{s1.GetHashCode()}"); Console.WriteLine($"{index}:{s2.GetHashCode()}"); Assert.AreEqual(s1.GetHashCode(), s2.GetHashCode()); threadScope = Thread.GetData(Thread.GetNamedDataSlot(CO2NET.SenparcDI.SENPARC_DI_THREAD_SERVICE_Scope)) as IServiceScope; Console.WriteLine("ServiceScope:" + threadScope.GetHashCode()); Console.WriteLine("ServiceProcider:" + threadScope.ServiceProvider.GetHashCode()); Console.WriteLine("-----------------"); finishedThread++; }); thread.Start(); } while (finishedThread != threadsCount) { } //单线程内HashCode相同 }