咱們在Startup類裏面能夠看到那麼一句話:ide
// This method gets called by the runtime. Use this method to add services to the container.
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddSession(); }
意思就是:要把服務注入容器裏面去【core內置IOC】:當前方法被運行時環境調入,把服務添加到container容器裏面去,IServiceCollection其實就是個一個容器,那咱們是怎麼使用,怎麼解析呢???ui
要使用它就必需要有個接口,以及接口的實例,那咱們就來寫個接口實例:this
/// 容器的使用: /// 1.建立一個容器的實例; /// 2.註冊 /// 3.獲取服務
/// <summary> /// 容器的使用實例 /// </summary> /// <param name="args"></param> static void Main(string[] args) { { Console.WriteLine("容器的使用實例"); //1.建立一個容器的實例,須要添加NuGet【Microsoft.Extensions.DependencyInjection】,同時引用命名空間 IServiceCollection container = new ServiceCollection(); //2.註冊【註冊有4種方式,用Add添加的方式】 //第一種瞬時生命週期,每次獲取的對象都是一個新的對象 container.AddTransient<IServiceA, ServiceA>(); //第二種單例註冊,單例生命週期:在容器中永遠只有當前這一個 container.AddSingleton<IServiceB, ServiceB>(); //第三種做用域註冊,生命週期:當前請求做用域,只有當前這個實例,除非二次請求,或者做用域不同 container.AddScoped<IServiceC, ServiceC>(); //第四種:跟單例的生命週期同樣 container.AddSingleton<IServiceD>(new ServiceD()); //3.獲取服務【Alt+Shift 豎列選擇】【ctrl+K+D:自動格式化】 ServiceProvider provider = container.BuildServiceProvider(); IServiceA TestA = provider.GetService<IServiceA>(); IServiceB TestB = provider.GetService<IServiceB>(); IServiceC TestC = provider.GetService<IServiceC>(); IServiceD TestD = provider.GetService<IServiceD>(); //作比較 IServiceA TestA1 = provider.GetService<IServiceA>(); IServiceB TestB1 = provider.GetService<IServiceB>(); IServiceC TestC1 = provider.GetService<IServiceC>(); IServiceD TestD1 = provider.GetService<IServiceD>(); Console.WriteLine($"瞬時生命週期比較,結果:{Object.ReferenceEquals(TestA, TestA1)}"); Console.WriteLine($"單例1的生命週期比較,結果:{ReferenceEquals(TestB, TestB1)}"); Console.WriteLine($"單例2的生命週期比較,結果:{Object.ReferenceEquals(TestD, TestD1)}"); //同一個做用域比較 Console.WriteLine($"同做用域生命週期比較,結果:{Object.ReferenceEquals(TestC, TestC1)}"); //新建一個做用域 IServiceScope scope = provider.CreateScope(); IServiceC TestC2 = scope.ServiceProvider.GetService<IServiceC>(); //不一樣做用域比較 Console.WriteLine($"不一樣做用域生命週期比較,結果:{Object.ReferenceEquals(TestC,TestC2)}"); } Console.ReadLine(); }
結果: spa
這邊單獨寫了兩個接口類庫:Core.Interface,Core.Service3d
Core.Interface code
public interface IServiceA { void Show(); }
public interface IServiceB { void Show(); }
public interface IServiceC { void Show(); }
public interface IServiceD { void Show(); }
Core.Service:對象
public class ServiceA : IServiceA { public void Show() { Console.WriteLine("ServiceA"); } }
public class ServiceB : IServiceB { public ServiceB(IServiceA iservice) { } public void Show() { Console.WriteLine("This's ServiceB"); } }
public class ServiceC : IServiceC { public ServiceC(IServiceB iservice) { } public void Show() { Console.WriteLine("This's ServiceC"); } }
public class ServiceD : IServiceD { public void Show() { Console.WriteLine("ServiceD"); } }