Reputation: 18205
I have an Azure Function app (using the newer .net class library
approach) that I initialize with a static constructor so as to share generated resources.
Official documentation recommends sharing resources like an HttpClient
in a web api.
The discussion at the bottom of the docs on Azure Functions C# script developer reference mentions placing an HttpClient
in a static variable to prevent re-instantiation on each request since it is thread-safe.
I'm wondering two things.
Is a static constructor ok for initializing my expensive to 'set-up' resources used by all requests?
If this approach is ok, how should error logging be configured in a static constructor if the initialization of these resources fails?
Here is my class definition
public static class HttpSubmissionTrigger
{
private static readonly SendGridClient sendGridClient;
private static readonly Func<IDictionary<string, object>, string> template;
private static readonly EmailAddress senderEmail;
private static readonly string emailTitle;
private static readonly HttpResponseMessage errorResponse;
static HttpSubmissionTrigger()
{
// ... initialization of above static members here
}
public static async Task<HttpResponseMessage> Run(...)
{
// ... use static members here to send emails, respond to client
}
}
I perform error logging in my Run
method using the DI of the TraceWriter
, which works fine. I can use this to view errors in the Azure portal console for the function, but static constructors can't have parameters, so that approach won't work for resource initialization.
There is another reference to this question in the Azure function docs but the response was to ask the question here.
Upvotes: 6
Views: 2999
Reputation: 12538
You're not limited to the static constructor to perform initialization logic for shared resources.
One approach, of a few possible, would be to have a class managing those resources for you, where you'd perform static initialization when your function is invoked, passing loggers and other relevant information, ensuring appropriate checks to avoid double initialization.
The function filters feature we'll be releasing soon will help with these scenarios as well: https://github.com/Azure/azure-webjobs-sdk/wiki/Function-Filters
Upvotes: 4