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 { }

  

posted @   孤海飞雁  阅读(123)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示