1. 程式人生 > 實用技巧 >Microsoft.Extensions.DependencyInjection的Singleton依賴注入關係,只是對於同一個ServiceProvider是單例的

Microsoft.Extensions.DependencyInjection的Singleton依賴注入關係,只是對於同一個ServiceProvider是單例的

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變數 using (serviceProvider = services.BuildServiceProvider()) { peopleA = serviceProvider.GetService<IPeople>(); } using (serviceProvider = services.BuildServiceProvider()) { peopleB = serviceProvider.GetService<IPeople>(); } 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依賴注入關係,可以參考這裡