在Azure函数中使用类

时间:2017-06-20 15:45:45

标签: c# azure azure-functions

我想创建一个外部日志记录类,它通过构造函数初始化来设置。然后,我希望能够在整个函数生命周期中多次使用此类。

e.g。

using System.Net;

private static Logger logger;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, 
TraceWriter log, ExecutionContext executionContext)
{
    log.Info("C# HTTP trigger function processed a request.");

    string invocationId = executionContext.InvocationId.ToString();
    logger = new Logger(invocationId);

    logger.Log("Start"); 

    // parse query parameter
    string name = req.GetQueryNameValuePairs()
    .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
    .Value;

    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    name = name ?? data?.name;

    logger.Log("Finish");

    return name == null
    ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
    : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}

public class Logger
{
    private string _invocationId;

    public Logger(string invocationId) 
    {
        _invocationId = invocationId;
    }

    public void Log(string message)
    {   
        message = $"{_invocationId} | {message}";
        // log to Splunk
    }
}

这是使用我的Logger类的正确方法&#34;全球&#34;整个功能?

private static Logger logger;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, 
TraceWriter log, ExecutionContext executionContext)
{
    log.Info("C# HTTP trigger function processed a request.");

    string invocationId = executionContext.InvocationId.ToString();
    logger = new Logger(invocationId);

新课程是否有任何影响?

这是我想要实现的简化版本。

1 个答案:

答案 0 :(得分:3)

您的代码没有多大意义:您有一个静态字段,但是您在每次调用时都会分配它。第二次调用可能会覆盖第一次调用所创建的值,因此您可能会得到不可预测的结果。

您应该选择:您的字段是静态的,您创建一次然后在每次后续调用时使用该实例;或者您只需创建一个局部变量并按照现在的方式使用它。

除非您确实需要跨请求共享内容,否则首选第二个选项。如果可能,请避免使用共享状态。

更新:

根据您评论中的问题,您可以执行以下操作:

<http://www.w3.org/2000/09/xmldsig#:foo />

我不是这种风格的特别粉丝,但如果这就是你想要的,那就可以了。

相关问题