private static void TryOutSingleton() { Console.WriteLine($"RUNNING {nameof(TryOutSingleton)}"); ServiceCollection services = new ServiceCollection(); // 准备好我们的容器 services.AddSingleton <MyClass>(); //把MyClass注册为 Singleton 生命周期 ConcurrentBag <MyClass> bag = GetObjectsFromDI(services); // 调用我们准备好的方法,用若干线程从 IServiceProvider 中获取 MyClass 实例,并加入到集合 Console.WriteLine($"All items in collection are IDENTICAL: {bag.AreIdentical()}"); // 验证集合中的所有元素是否指向内存中的同一个对象。 }
private static void TryOutScoped() { Console.WriteLine($"RUNNING {nameof(TryOutScoped)}"); ServiceCollection services = new ServiceCollection(); services.AddSingleton <MySingleton>(); services.AddTransient <MyTransient>(); services.AddScoped <MyScoped>(); IServiceProvider sp = services.BuildServiceProvider(); // 线程1执行 ConcurrentBag <MySingleton> thread1SingletonBag = new ConcurrentBag <MySingleton>(); ConcurrentBag <MyTransient> thread1TransientBag = new ConcurrentBag <MyTransient>(); ConcurrentBag <MyScoped> thread1ScopedBag = new ConcurrentBag <MyScoped>(); Thread thread1 = new Thread(RunPerThreadWithScopedLifetime); thread1.Start(new Tuple <IServiceProvider, ConcurrentBag <MySingleton>, ConcurrentBag <MyTransient>, ConcurrentBag <MyScoped> >(sp, thread1SingletonBag, thread1TransientBag, thread1ScopedBag)); // 线程2执行 ConcurrentBag <MySingleton> thread2SingletonBag = new ConcurrentBag <MySingleton>(); ConcurrentBag <MyTransient> thread2TransientBag = new ConcurrentBag <MyTransient>(); ConcurrentBag <MyScoped> thread2ScopedBag = new ConcurrentBag <MyScoped>(); Thread thread2 = new Thread(RunPerThreadWithScopedLifetime); thread2.Start(new Tuple <IServiceProvider, ConcurrentBag <MySingleton>, ConcurrentBag <MyTransient>, ConcurrentBag <MyScoped> >(sp, thread2SingletonBag, thread2TransientBag, thread2ScopedBag)); // 等待执行完毕 thread1.Join(); thread2.Join(); // 验证所有 MySingleton 的实例都指向内存里同一个对象 IEnumerable <MySingleton> singletons = thread1SingletonBag.Concat(thread2SingletonBag); Console.WriteLine($"Singleton: {singletons.Count()} objects are IDENTICAL? {singletons.AreIdentical()}"); // 验证所有 MyTransient 的实例都各不相同 IEnumerable <MyTransient> transients = thread1TransientBag.Concat(thread2TransientBag); Console.WriteLine($"Transient: {transients.Count()} objects are DIFFERENT? {transients.AreDifferent()}"); // 对于Scoped生命周期,每个线程集合内的实例应该指向内存里同一个对象,而2个线程集合里的实例应该是不同的。 Console.WriteLine($"collection of thread 1 has {thread1ScopedBag.Count} objects and they are IDENTICAL: {thread1ScopedBag.AreIdentical()}"); Console.WriteLine($"collection of thread 2 has {thread2ScopedBag.Count} objects and they are IDENTICAL: {thread2ScopedBag.AreIdentical()}"); Console.WriteLine($"the first object from thread 1 and the first object from thread 2 are IDENTICAL: {Object.ReferenceEquals(thread1ScopedBag.First(), thread2ScopedBag.First())}"); }