在使用依赖项注入(例如在 ASP.NET 中)时,如何异步关闭和处置 Azure ServiceBusClient 和 ServiceBusSender 单例?

问题描述 投票:0回答:2

我想在 .NET 7 应用程序中使用 Azure 服务总线,例如使用依赖注入的 ASP.NET Core Web API 或 Worker Service。

官方文档建议将

ServiceBusClient
ServiceBusSender
注册为单例:

与服务交互的服务总线对象,例如 ServiceBusClient、ServiceBusSender、ServiceBusReceiver 和 ServiceBusProcessor,应注册为单例(或实例化一次并共享)以进行依赖注入。

还说依赖项将并且必须由容器通过单例的

IDisposable.Dispose()

容器负责清理它创建的类型,并在 IDisposable 实例上调用 Dispose。从容器解析的服务永远不应该由开发人员处置。如果类型或工厂注册为单例,容器会自动处理单例。

现在,

ServiceBusClient
ServiceBusSender
的问题是,两者都没有实现
IDisposable
,而是实现
IAsyncDisposable
。 我找不到任何关于依赖注入容器在关闭应用程序时是否也会自动调用(并等待)
IAsyncDisposable.DisposeAsync()
的文档。

是这样吗?

如果没有,我还应该如何在

Services resolved from the container should never be disposed by the developer
时处置 Azure 服务总线单例?

c# asp.net dependency-injection azureservicebus dispose
2个回答
2
投票

来自医生

关于依赖注入,在 IServiceCollection 中注册服务时,服务生命周期会代表您隐式管理。 IServiceProvider 和相应的 IHost 协调资源清理。具体来说, IDisposable 和 IAsyncDisposable 的实现在其指定生命周期结束时被正确处置。


0
投票
public async ValueTask DisposeAsync() { if (_client != null) { await _client.DisposeAsync(); } if (_sender != null) { await _sender.DisposeAsync(); } GC.SuppressFinalize(this); }
    
© www.soinside.com 2019 - 2024. All rights reserved.