微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.NET Core 依赖注入容器不调用 Dispose()

如何解决.NET Core 依赖注入容器不调用 Dispose()

我不知道为什么在程序结束时没有调用 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”
我正在做一些工作

非常感谢任何帮助。


使其正常工作的更改如下:

  1. Idisposable 添加IConsoleService
public interface IConsoleService,Idisposable
{
    void Run(string[] args);
}
  1. 并将其从 ConsoleService
  2. 删除
public class ConsoleService : IConsoleService
{
  1. IHost 变量包装在 using 语句中或调用 host.dispose()

  2. 使用 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);
   }
 });
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。