当使用 DI 来添加使用AddScoped或 的服务时AddSingleton,该服务是否需要实现IDisposable(即使它不使用任何非托管资源(例如文件))?
从 Microsoft Docs 找到以下示例:
// 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 …Run Code Online (Sandbox Code Playgroud)