上节,我们提到,容器中有3种不同生命周期,分别是Singleton、Scoped和Transient。那么,你知道这3种类型的对象的释放时机和坑吗?
Table of Contents
IServiceScope接口
.NET Core中,管理作用域的是接口IServiceScope,该接口明确表示,其会调用IDisposable.Disposable()方法来结束掉当前作用的生命周期。
实现IDisposable接口类型的释放
- DI只负责释放由其创建的对象的实例
- DI在容器或子容器释放时,释放由其创建的对象实例
代码演示理解
下面,我们通过代码来分别理解3种对象的释放时机。
首先,我们定义一个方法,用fromServices来获取对象2次,以对比是否有新对象产生
[HttpGet]
public int GetService([FromServices] IOrderService orderService1,
[FromServices] IOrderService orderService2)
{
Console.WriteLine("=======创建子容器对象========");
using (IServiceScope scope=HttpContext.RequestServices.CreateScope())
{
var service = scope.ServiceProvider.GetService<IOrderService>();
var service1= scope.ServiceProvider.GetService<IOrderService>();
var service2= scope.ServiceProvider.GetService<IOrderService>();
}
Console.WriteLine("============子容器对象释放完成===========");
Console.WriteLine("接口处理结束");
return 1;
}
Scoped
先以Scoped类型为例,我们在ConfigureService里添加Scoped类型的对象
services.AddScoped<IOrderService, OrderService>();
运行程序后,我们观察输出
=======创建子容器对象========
DisposableOrderService Disposabled:38716773
============子容器对象释放完成===========
接口处理结束
DisposableOrderService Disposabled:37686956
从以上可以看出,我们在方法内的using部分成功创建了Scoped对象,该对象在using结束后已经得到释放,我们需要注意的是第二行的disposable输出,从该行位置可以看出,我们在ConfigureService中注册的对象,在接口方法执行完毕后才得到释放,与Scoped模式的定义相符。
Singleton
其次,我们来注册一个Singleton对象试试,根据我们的预测应该是没有任何的释放输出的,因为,Singleton对象在根容器释放时才会释放
services.AddSingleton<IOrderService, OrderService>();
结果如下,和期望一致。
=======创建子容器对象========
============子容器对象释放完成===========
接口处理结束
Transient
我们在来看Transient模式
services.AddTransient<IOrderService, OrderService>();
根据我们的判断,瞬时模式,每次都会获取一个新的对象,那么这里,应该一共会有5次释放动作。
运行结果如下
=======创建子容器对象========
DisposableOrderService Disposabled:36550596
DisposableOrderService Disposabled:50947826
DisposableOrderService Disposabled:28203839
============子容器对象释放完成===========
接口处理结束
DisposableOrderService Disposabled:12451586
DisposableOrderService Disposabled:59782618
这里我们可以看出,在using期间创建了3个Transient对象,并最终全部得到释放。
Singleton释放时机验证
上面我们提到,Singleton对象在根容器退出时才会释放,那么,我们如何确定其是否释放呢?
我们可以通过IHostApplicationLifetime来结束程序的生命周期,以判断其输出是否包含对Singleton的释放行为,我们定义如下方法
[HttpGet]
public void appExit([FromServices] IHostApplicationLifetime hostApplicationLifetime,
[FromQuery]bool stop)
{
if (stop)
{
hostApplicationLifetime.StopApplication();
}
//return 1;
}
并在执行上述方法之后,再通过浏览器访问该方法来结束程序,在访问地址后加stop=true参数即可模拟程序退出。如
http://localhost:5000/weatherforecast/appexit?stop=true
这里,我们先看看单例下的执行结果
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: E:\StydyDemos\Samples\CoreSamples\03_DependencyInjectionScopeAndDisposableDemo
=======创建子容器对象========
============子容器对象释放完成===========
接口处理结束
info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
DisposableOrderService Disposabled:62103957
E:\StydyDemos\Samples\CoreSamples\03_DependencyInjectionScopeAndDisposableDemo\bin\Debug\netcoreapp3.1\03_DependencyInjectionScopeAndDisposableDemo.exe (进程 21908)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
从这里,我们可以看出,Singleton对象在程序退出时得到了释放。
其实,Scoped和Transient模式的注册,释放行为都是在对象释放时,而不是程序退出时,如下
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: E:\StydyDemos\Samples\CoreSamples\03_DependencyInjectionScopeAndDisposableDemo
=======创建子容器对象========
DisposableOrderService Disposabled:33592719
============子容器对象释放完成===========
接口处理结束
DisposableOrderService Disposabled:18075529
info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
E:\StydyDemos\Samples\CoreSamples\03_DependencyInjectionScopeAndDisposableDemo\bin\Debug\netcoreapp3.1\03_DependencyInjectionScopeAndDisposableDemo.exe (进程 19136)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
避坑指南
既然Transient每次都会创建一个新的对象,那么我们就要避免在根容器内获取Transient的对象,因为这些对象会一直保留直到根容器退出时才会释放,会导致程序的性能问题
如下,若再Configure内定义如下语句
var service = app.ApplicationServices.GetService<IOrderService>();
var service1 = app.ApplicationServices.GetService<IOrderService>();
var service2 = app.ApplicationServices.GetService<IOrderService>();
则这3个对象的退出如下
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: E:\StydyDemos\Samples\CoreSamples\03_DependencyInjectionScopeAndDisposableDemo
info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
DisposableOrderService Disposabled:49538252
DisposableOrderService Disposabled:62696216
DisposableOrderService Disposabled:31071611
E:\StydyDemos\Samples\CoreSamples\03_DependencyInjectionScopeAndDisposableDemo\bin\Debug\netcoreapp3.1\03_DependencyInjectionScopeAndDisposableDemo.exe (进程 11356)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
建议
- 避免在根容器获取实现了IDisposable接口的瞬时服务。
- 避免手动创建实现了IDisposable对象,应使用容器来管理其生命周期。
这里在演示一下手动创建对象的情况
IOrderService order = new OrderService();
services.AddSingleton<IOrderService>(order);
直接调用退出程序的方法,得到如下结果,可以看出并没有释放手动创建的对象
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: E:\StydyDemos\Samples\CoreSamples\03_DependencyInjectionScopeAndDisposableDemo
info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
E:\StydyDemos\Samples\CoreSamples\03_DependencyInjectionScopeAndDisposableDemo\bin\Debug\netcoreapp3.1\03_DependencyInjectionScopeAndDisposableDemo.exe (进程 10840)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
本节内容到此结束,下一节,介绍使用第三方的容器框架Autofac来增强容器能力以及引入切面编程(AOP)的能力。
源码可访问
https://github.com/IronMarmot/Samples/tree/master/CoreSamples
更多课程详细内容,可识别下方二维码购买。
【扫描二维码购买课程,可后台留言获得10元红包返现。】
部分内容来源于网络,侵删。
更多精彩内容,请微信搜索攻城狮客栈 或扫描下方二维码
------------------------------------------------------------------------------
公众号:攻城狮客栈
CSDN:画鸡蛋的不止达芬奇
让我们一起变的更优秀。