Conditions to Trigger Analyzer
Within a [Function]-decorated method, where a new DocumentClient is instantiated..
public static class CosmosDBWrong
{
[FunctionName("CosmosDBWrong")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string endpointUri = "testCosmosDB";
string primaryKey =
var docDBClient = new DocumentClient(new Uri(endpointUri), primaryKey, new ConnectionPolicy()
{
MaxConnectionLimit = 100,
ConnectionMode = ConnectionMode.Gateway,
ConnectionProtocol = Protocol.Tcp,
RetryOptions = new RetryOptions() { MaxRetryAttemptsOnThrottledRequests = 3, MaxRetryWaitTimeInSeconds = 60 }
});
string responseMessage = "Hello from CosmosDB";
return new OkObjectResult(responseMessage);
}
}
Diagnostic Level
Warning
How to Fix Violations
Lazy static instantiation outside of [Function] method:
using Microsoft.Azure.Documents.Client;
private static Lazy<DocumentClient> lazyClient = new Lazy<DocumentClient>(InitializeDocumentClient);
private static DocumentClient documentClient => lazyClient.Value;
private static DocumentClient InitializeDocumentClient()
{
// Perform any initialization here
var uri = new Uri("example");
var authKey = "authKey";
return new DocumentClient(uri, authKey);
}
public static async Task Run(string input)
{
Uri collectionUri = UriFactory.CreateDocumentCollectionUri("database", "collection");
object document = new { Data = "example" };
await documentClient.UpsertDocumentAsync(collectionUri, document);
// Rest of function
}
Conditions to Trigger Analyzer Within a
[Function]
-decorated method, where a new DocumentClient is instantiated..Diagnostic Level Warning
How to Fix Violations
Whether to Supply Codefix Yes for 1, if possible for 2.
Associated Documentation https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections
When to Suppress Analyzer Rule This rule should not be suppressed.