作用域

  • IServiceScope

    • 作用域主要由 IServiceScope 对象去承载

      实现 IDisposable 接口类型的释放

  • DI 只负责释放由其创建的对象实例

  • **DI 在容器或子容器释放时,释放由其创建的对象实例

即:对象A 若是我们自己创建放在容器中的,容器不负责释放对象A,只有容器和子容器释放时才会释放对象A。容器的生命周期与其创建的对象生命周期时有对应关系的。

建议

  • 避免在根容器获取实现了 IDisposable 接口的瞬时服务;
  • 避免手动创建实现了 IDisposable 对象,应使用容器来管理其生命周期;

    实例对象

    1. public interface IDisposableService {}
    2. public class DisposableService : IDisposableService, IDisposable
    3. {
    4. public void Dispose()
    5. {
    6. Console.WriteLine($"IDisposableService Disposed:{this.GetHashCode()}");
    7. }
    8. }

    接口

    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
      private readonly ILogger<WeatherForecastController> _logger;
    
      public WeatherForecastController(ILogger<WeatherForecastController> logger)
      {
          _logger = logger;
      }
    
      [HttpGet]
      public void Get([FromServices] IDisposableService service, [FromServices] IHostApplicationLifetime lifetime,[FromQuery]bool stop = false)
      {
          //关闭程序
          if(stop)
              lifetime.StopApplication();
      }
    }
    

    Startup对象

    public class Startup
    {
      public Startup(IConfiguration configuration)
      {
          Configuration = configuration;
      }
    
      public IConfiguration Configuration { get; }
    
      // This method gets called by the runtime. Use this method to add services to the container.
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddControllers();
          services.AddSwaggerGen(c =>
          {
              c.SwaggerDoc("v1", new OpenApiInfo { Title = "StarupDemo", Version = "v1" });
          });
          //自己创建对象注入
          var server = new DisposableService();
          services.AddSingleton<IDisposableService>(server);
          //正常注册方式
          services.AddSingleton<IDisposableService, DisposableService>();
      }
    
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          //根容器创建 
          var s = app.ApplicationServices.GetService<IDisposableService>();
          var s2 = app.ApplicationServices.GetService<IDisposableService>();
    
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
              app.UseSwagger();
              app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "StarupDemo v1"));
          }
    
          app.UseRouting();
    
          app.UseAuthorization();
    
          app.UseEndpoints(endpoints =>
          {
              endpoints.MapControllers();
          });
      }
    }
    

    如上代码所示在 Startup.ConfigureServices 方法中有两种注册方式,分别为自己创建对象注入和正常的注册方式。这两种注册方式在调用Get(true)接口强制程序结束时,由自己创建对象注册的并不会执行 Dispose 方法,而正常注册的方式在程序结束时会释放对象调用 Dispose 方法。
    同时在 Startup.Configure 方法中创建了两个瞬时对象 s、s2 在调用 Get(false) 接口时,并不会调用 Dispose 方法,也就是说根容器中瞬时对象 s、s2 并没有被释放,只有当执行 Get(true) 强制关闭程序的时候,s、s2 才会被回收。