47 lines
2.1 KiB
Plaintext

== Why is this an issue?
To avoid holding more connections than necessary and to avoid potentially exhausting the number of available sockets when using `HttpClient`, `DocumentClient`, `QueueClient`, `ConnectionMultiplexer` or Azure Storage clients, consider:
* Creating a single, thread-safe static client that every Azure Function invocation can use. Provide it in a shared class when different Azure Functions need it.
* Instantiate the client as a thread-safe Singleton or a pool of reusable instances and use it with dependency injection.
These classes typically manage their own connections to the resource, and thus are intended to be instantiated once and reused throughout the lifetime of an application.
=== Noncompliant code example
[source,csharp]
----
public class HttpExample
{
[FunctionName("HttpExample")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest request)
{
HttpClient httpClient = new HttpClient(); // Noncompliant
var response = await httpClient.GetAsync("https://example.com");
// rest of the function
}
}
----
=== Compliant solution
[source,csharp]
----
public class HttpExample
{
[FunctionName("HttpExample")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest request, IHttpClientFactory clientFactory)
{
var httpClient = clientFactory.CreateClient();
var response = await httpClient.GetAsync("https://example.com");
// rest of the function
}
}
----
== Resources
* https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections?tabs=csharp#static-clients[Manage connections in Azure Functions: Static Clients]
* https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#service-lifetimes[Azure Functions - Dependency Injection: Service Lifetimes]
* https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/[Improper Instantiation antipattern]