【发布时间】:2017-08-18 16:57:46
【问题描述】:
我有一个 Azure Function 应用程序(使用较新的 .net class library 方法),我使用静态构造函数对其进行初始化,以便共享生成的资源。
官方文档建议共享资源,例如HttpClient in a web api。
Azure Functions C# script developer reference 文档底部的讨论提到将 HttpClient 放在静态变量中以防止对每个请求进行重新实例化,因为它是线程安全的。
我想知道两件事。
是否可以使用静态构造函数来初始化所有请求使用的昂贵的“设置”资源?
如果这种方法没问题,如果这些资源的初始化失败,应该如何在静态构造函数中配置错误日志?
这是我的类定义
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
}
}
我使用TraceWriter 的DI 在我的Run 方法中执行错误记录,该方法工作正常。我可以使用它在 Azure 门户控制台中查看函数的错误,但静态构造函数不能有参数,因此该方法不适用于资源初始化。
Azure function docs 中有另一个关于这个问题的参考,但回复是在这里问这个问题。
【问题讨论】:
-
我有一些静态类和方法来处理诸如访问表存储之类的事情,并在应用程序内的函数之间共享。这些类期望传递一个 TraceWriter,所以我选择扩展 TraceWriter 并创建一个直接将日志记录到表存储的类。我将 TablestorageTraceWriter 用于静态构造函数中的日志。您也可以让它写入 blob 存储或类似文件中的文件。
标签: c# azure azure-functions