本文介绍了持久功能v2.0中未注入ILogger的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻,我正在尝试向Azure持久函数添加ILoggerILogger<>以便在活动函数中使用日志记录.

At the moment I'm trying to add an ILogger or ILogger<> to a Azure Durable Function so as to use logging in Activity Functions.

登录Orchestration函数的工作正常,并已注入方法本身,但是尝试为ILogger进行构造函数注入总是会导致Null异常.

Logging in the Orchestration Function works fine and is injected in the method itself, but attempts at constructor injection for ILogger always results in a Null Exception.

builder.Services.AddLogging();

以上内容在添加到启动文件(Bootstrapper)中时似乎不起作用,并且变体形式也不行:

The above does not seem to work when added to the Startup file (Bootstrapper) and neither does variations on:

builder.Services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));

有人解决了吗?

推荐答案

从启动文件中删除以下任一行:

Remove either of these lines from your Startup file:

builder.Services.AddLogging();
builder.Services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));

然后,无论您在何处注入ILogger,都使用ILogger<T>添加记录器正在注入的type,即:

Then, wherever you are injecting your ILogger, add the type that your logger is being injected into using ILogger<T> i.e:

public class Function1
{
    private readonly ILogger _logger;

    public Function1(ILogger<Function1> logger)
    {
        _logger = logger;
    }

    [FunctionName("Function1")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
    {
        _logger.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        return name != null
            ? (ActionResult)new OkObjectResult($"Hello, {name}")
            : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
    }
}

这篇关于持久功能v2.0中未注入ILogger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 00:46