Azure 函数、依赖注入、"there is no argument given that corresponds to the formal parameter"、dotnet 核心

Azure Function, Dependency Injection, "there is no argument given that corresponds to the formal parameter", dotnet core

我正在尝试从 Azure 函数调用存储库 class,但出现错误

There is no argument given that corresponds to the formal parameter

我从 .NET Core Web API 项目复制了存储库 class 结构,并且知道这与依赖注入有关。

存储库的构造函数 class 如下所示:

public CaseRepository(ILogger<CaseRepository> logger, IConfiguration configuration)
{
    _logger = logger;
    _configuration = configuration;
}

如何将其传递到 Azure 函数的静态方法中,就像我对 Web API 调用所做的那样:

[FunctionName("TestFunction")]
public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log, CaseRepository caseRepository)
{
    // ...
}

可以在Startupclass中定义依赖声明,如this file and later instead of defining the function as static define it normal class function. In the class constructor inject the required dependency. See this所示,供参考。

启动class

 [assembly: FunctionsStartup(typeof(YourNamespace.Startup))]

 namespace YourNamespace
 {
   public class Startup : FunctionsStartup
   {
      builder.Services.AddSingleton<ICaseRepository, CaseRepository>();
   }
 }

用法 - 这里 ICaseRepository 被注入到包含 Azure 函数的 class 中。

public class TestFunction
{
    private readonly ICaseRepository caseRepository;

    public TestFunction(ICaseRepository  caseRepository)
    {
        this.caseRepository= caseRepository;
    }

    [FunctionName("TestFunction")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        // ... use caseRepository instance
    }
}