在使用AddScoped
或AddSingleton
添加服务时,该服务是否需要实现IDisposable
接口(即使它没有使用任何非托管资源如文件)?
这里是从Microsoft文档中找到的示例:
// Services that implement IDisposable:
public class Service1 : IDisposable {}
public class Service2 : IDisposable {}
public class Service3 : IDisposable {}
public interface ISomeService {}
public class SomeServiceImplementation : ISomeService, IDisposable {}
public void ConfigureServices(IServiceCollection services)
{
// The container creates the following instances and disposes them automatically:
services.AddScoped<Service1>();
services.AddSingleton<Service2>();
services.AddSingleton<ISomeService>(sp => new SomeServiceImplementation());
// The container doesn't create the following instances, so it doesn't dispose of
// the instances automatically:
services.AddSingleton<Service3>(new Service3());
services.AddSingleton(new Service3());
}
如果我有这段代码会发生什么:
public class Service0 // (doesn't implement Disposable)
services.AddScoped<Service0>(); // what happens to it when request scope ends? Does it stay on the heap?
services.AddSingleton<Service0>(); // it lives till application dies
services.AddSingleton(new Service0()); // ??
services.AddSingleton<IConfigureOptions<Service0>>((ctx) =>
{
return new ConfigureNamedOptions<Service0>(null, (config) =>
{
// Do something here -- in debug mode it is executing this logic for each request
}} // it is returning "new Service0" when a request is made. Does it mean for each request it returns new object and keeps in heap memory or returns same previously created object?
IDisposable
接口。相反,必须实现IDisposable
应该是异常而非规范。 - Steven