Reputation: 917
Microsoft.Azure.Devices.ServiceClient
and Microsoft.Azure.Devices.RegistryManager
both have ConnectFromConnectionString
and CloseAsync
methods.
Should we use them like we use other .NET connection-close
patterns, such as ADO.NET connections, Redis connections, Sockets' etc.? When I use objects like those I try to Close
or Disposable.Dispose()
of them as soon as possible.
What's the upside and downside to doing the same with the Microsoft.Azure.Devices
objects when accessing the same IOT Hub? I have running code that treats the individual RegistryManager
and ServiceClient
instances as singletons, which are used throughout an application's lifetime -- which may be weeks or months. Are we short circuiting ourselves by keeping these objects "open" for this duration?
Upvotes: 3
Views: 303
Reputation: 37
As pointed by @David R. Williamson, and this discussion on GitHub, it is generally recommended to register RegistryManager
and ServiceClient
as singletons.
For ASP NET Core or Azure Functions, it can be done as follows at startup:
ConfigureServices(services)
{
services.AddSingleton<RegistryManager>(RegistryManager.CreateFromConnectionString("connectionstring"));
}
Upvotes: 1
Reputation: 101
I'm on the Azure IoT SDK team. We recommend keeping the service client instances around, depending on your usage pattern.
While it is generally fine to init/close/dispose the Azure IoT service clients, you can run into the HttpClient socket exhaustion problem. We've done work to prevent it from happening if you keep a singleton of the client around, but when the client is disposed 2 HttpClient instances are also disposed.
There's little harm in keeping them around and will save your program execution time in init/dispose.
We're working on a v2 where we'll allow the user to pass in their own copy of HttpClient, so you could keep that around and shut down our client more frequently.
Upvotes: 0