使用ServiceCollection 注入AddTransient,AddScoped,AddSingleton 三不同生命周期的的对象
Transient 最先释放
Scope 随后
Singleton 最后
using (var sc = new ServiceCollection() .AddScoped<IA, A>() .AddSingleton<IB, B>() .AddTransient<IC, C>() .BuildServiceProvider() ) { //var Obja = sc.GetService<IA>()!; //var Objb = sc.GetService<IB>()!; //var Objc = sc.GetService<IC>()!; //sc.AddScoped<IA, A>(); //sc.AddSingleton<IB, B>(); //sc.AddTransient<IC, C>(); using (var cs = sc.CreateScope()) //创建服务) { var sp= cs.ServiceProvider; // A Obja = (A)sp.GetService<IA>()!; var ChildObja = sp.GetService<IA>()!; var ChildObjb = sp.GetService<IB>()!; var ChildObjc = sp.GetService<IC>()!; // Obja.run(); Console.WriteLine(); } } public class Base : IDisposable { public Base() => Console.WriteLine($" 对象已 {GetType().Name} 创建"); public void Dispose() => Console.WriteLine($" 对象已 {GetType().Name} 释放."); } public interface IA { } public interface IB { } public interface IC { } public class A: Base,IA, IDisposable { public void run() => Console.Write($"{GetType().Name} 运行啦"); } public class B: Base,IB, IDisposable { } public class C : Base, IC, IDisposable { }
标签:释放,生命周期,sp,GetService,sc,Base,var,IOC,public From: https://www.cnblogs.com/liujian1368928/p/16777642.html