S6420 — Client instances should not be recreated on each Azure Function invocation

Language
C#
Type
Code smell
Severity
Major
Tags
azure, bad-practice, design

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:

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


    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


    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

↑ Back to top