在Microsoft.Extensions.DependencyInjection中,Singleton代表单例依赖注入,但是这个单例也只是对于相同的ServiceProvider对象而言。
假设我们的项目中有接口IPeople和实现类People,它们之间的依赖注入关系是Singleton的。
新建一个.NET Core控制台项目,代码如下所示:
using Microsoft.Extensions.DependencyInjection; using System; namespace NetCoreDISingletonDemos { interface IPeople { } class People : IPeople { } class Program { static void Main(string[] args) { IServiceCollection services = new ServiceCollection(); services.AddSingleton<IPeople, People>();//注册接口IPeople和类People的关系为Singleton IPeople peopleA = null; IPeople peopleB = null; ServiceProvider serviceProvider = null; //下面测试在同一个ServiceProvider中获取IPeople对象两次,赋值给peopleA和peopleB变量 using (serviceProvider = services.BuildServiceProvider()) { peopleA = serviceProvider.GetService<IPeople>(); peopleB = serviceProvider.GetService<IPeople>(); Console.WriteLine("peopleA==peopleB?{0}", (peopleA == peopleB).ToString());//True } peopleA = null; peopleB = null; //下面测试在不同的ServiceProvider中获取IPeople对象两次,赋值给peopleA和peopleB变量 ServiceProvider serviceProviderA = null; ServiceProvider serviceProviderB = null; using (serviceProviderA = services.BuildServiceProvider()) { peopleA = serviceProviderA.GetService<IPeople>(); } using (serviceProviderB = services.BuildServiceProvider()) { peopleB = serviceProviderB.GetService<IPeople>(); } Console.WriteLine("serviceProviderA==serviceProviderB?{0}", (serviceProviderA == serviceProviderB).ToString());//False Console.WriteLine("peopleA==peopleB?{0}", (peopleA == peopleB).ToString());//False peopleA = null; peopleB = null; //下面测试用同一个ServiceProvider创建的不同IServiceScope,来获取IPeople对象两次,赋值给peopleA和peopleB变量 using (serviceProvider = services.BuildServiceProvider()) { IServiceScope serviceScopeA = null; IServiceScope serviceScopeB = null; using (serviceScopeA = serviceProvider.CreateScope()) { peopleA = serviceScopeA.ServiceProvider.GetService<IPeople>(); } using (serviceScopeB = serviceProvider.CreateScope()) { peopleB = serviceScopeB.ServiceProvider.GetService<IPeople>(); } Console.WriteLine("serviceScopeA.ServiceProvider==serviceScopeB.ServiceProvider?{0}", (serviceScopeA.ServiceProvider == serviceScopeB.ServiceProvider).ToString());//False Console.WriteLine("peopleA==peopleB?{0}", (peopleA == peopleB).ToString());//True } Console.WriteLine("Press any key to end..."); Console.ReadKey(); } } }
执行结果如下所示:
可以看到:
- 我们使用同一个ServiceProvider获取到的两个IPeople对象是相同的。
- 我们使用不同的ServiceProvider获取到的两个IPeople对象是不同的。
- 我们使用同一个ServiceProvider创建的不同IServiceScope,获取到的两个IPeople对象是相同的。
关于Microsoft.Extensions.DependencyInjection的Singleton依赖注入关系,可以参考这里。