我們在Startup類里面可以看到那么一句話:
// 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其實就是個一個容器,那我們是怎么使用,怎么決議呢???
要使用它就必須要有個介面,以及介面的實體,那我們就來寫個介面實體:
/// 容器的使用: /// 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(); }
結果:

這邊單獨寫了兩個介面類別庫:Core.Interface,Core.Service
Core.Interface
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"); } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/229622.html
標籤:.NET技术
