问题描述
我不知道为什么在程序结束时没有调用 dispose()
。我编写了一个控制台应用程序来帮助测试 Azure Functions 应用程序。其中一个类实现了 Idisposable
,但从未调用 dispose()
。我扩展了我的示例以查看实现 Idisposable
的依赖服务是否调用了它的 dispose()
方法,而它没有调用。我今天早上刚更新到 16.9.4,目标框架是 .NET 5。这是示例代码:
public class CustomOptions
{
public const string Section = "CustomSettings";
public string Url { get; set; }
public bool UseHttps { get; set; }
}
public interface IdisposableService
{
void DoSomething();
}
public class disposableService : IdisposableService,Idisposable
{
public void dispose()
{
Console.WriteLine("disposing a disposable service");
GC.SuppressFinalize(this);
}
public void DoSomething()
{
Console.WriteLine("I'm doing some work");
}
}
public interface IConsoleService
{
void Run(string[] args);
}
public class ConsoleService : IConsoleService,Idisposable
{
private readonly ILogger<ConsoleService> _logger;
private readonly CustomOptions _options;
private readonly IdisposableService _service;
public ConsoleService(IdisposableService service,ILogger<ConsoleService> logger,IOptions<CustomOptions> options)
{
_service = service;
_logger = logger;
_options = options.Value;
}
public void dispose()
{
Console.WriteLine($"disposing {nameof(ConsoleService)}");
GC.SuppressFinalize(this);
}
public void Run(string[] args)
{
_logger.Loginformation("The application is Now starting {Start}",DateTime.Now);
Console.WriteLine($"The Url in the settings file is '{_options.Url}'");
_service.DoSomething();
}
}
class Program
{
static void Main(string[] args)
{
IHost host = Host.CreateDefaultBuilder()
.ConfigureServices((context,services) =>
{
services.Configure<CustomOptions>(
context.Configuration.GetSection(CustomOptions.Section));
services.AddTransient<IdisposableService,disposableService>();
services.AddTransient<IConsoleService,ConsoleService>();
services.AddLogging();
services.AddOptions();
})
.Build();
IConsoleService service =
ActivatorUtilities.CreateInstance<ConsoleService>(host.Services);
service.Run(args);
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Warning"
}
},"CustomSettings": {
"Url": "www.contoso.com","UseHttps": true
}
}
程序的输出是:
信息:ConsoleApp.ConsoleService[0]
申请现已开始 04/14/2021 10:30:54
设置文件中的 Url 是“www.contoso.com”
我正在做一些工作
非常感谢任何帮助。
使其正常工作的更改如下:
public interface IConsoleService,Idisposable
{
void Run(string[] args);
}
- 并将其从
ConsoleService
中删除
public class ConsoleService : IConsoleService
{
-
使用
IServiceProvider.GetService<>()
而不是ActivatorUtilities.CreateInstance<>()
host.Services.GetService<IConsoleService>().Run(args);
host.dispose();
解决方法
这是一个仅使用 ServiceCollection 的示例
_getContacts() async {
List<Contact> _contacts =
(await ContactsService.getContacts(withThumbnails: false)).toList();
setState(() {
contacts.addAll(_contacts);
for(var i=0; i<contacts.length; i++){
print(contacts[i].displayName);
}
});
}