接着上一篇文章继续:
3.以Singleton方式注入对象:
第一次请求时创建对象,且app关闭时才释放该对象
//工厂注入方式:第一次请求时创建对象,且app关闭时才释放该对象
services.AddSingleton<IOrderService>(x=>new DisposableOrderService());
/// <summary>
/// 演示Singleton注入方式的对象的释放
/// </summary>
/// <param name="hostApplicationLifetime"></param>
/// <param name="stop"></param>
/// <returns></returns>
[HttpGet("TestDISingleton")]
public int TestDISingleton([FromServices] IHostApplicationLifetime hostApplicationLifetime,
[FromQuery] bool stop = false)
{
if (stop) {
hostApplicationLifetime.StopApplication();
}
//return Enumerable.Range(1, 5).Select(index => new WeatherForecast
//{
// Date = DateTime.Now.AddDays(index),
// TemperatureC = rng.Next(-20, 55),
// Summary = Summaries[rng.Next(Summaries.Length)]
//})
//.ToArray();
return 10;
}
进入了Dispose方法,且app关闭
4.演示手工创建对象,然后放到DI容器中,这种方式不会由DI容器销毁
var orderService = new DisposableOrderService();
services.AddTransient(x => orderService);
发现应用关闭,也没调用Dispose方法