IOC 生命周期和释放
使用ServiceCollection 注入AddTransient,AddScoped,AddSingleton 三不同生命周期的的对象
Transient 最先释放
Scope 随后
Singleton 最后
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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 { } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下