直接在函数方法(Azure 函数)中注入 DI 实例



我想直接在 Azure 函数方法/主体中注入对象的实例,如下所示:

[FunctionName("StartJob")]
public async Task<IActionResult> Start(
[HttpTrigger(AuthorizationLevel.Function, "Post", Route = "v1/job")] HttpRequest req,
IStartJobHandler handler)
{
...

但是当我这样做时,我遇到了运行时错误:

The 'StartJob' function is in error: Microsoft.Azure.WebJobs.Host: Error indexing method 'StartJob'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'handler' to type IStartJobHandler. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

如果我在构造函数中注入相同的实例 - 一切都很好。(所以没有必要建议我检查我的启动类等等:)(

不过我不想注入构造函数。因为实例只属于一个特定的函数,并且想法是在函数之间隔离实例。

所以,问题是:我是否可以直接在 azure 函数方法中注入自定义类,而无需编写额外的代码,例如 ILogger:

[FunctionName("StartJob")]
public async Task<IActionResult> Start(
[HttpTrigger(AuthorizationLevel.Function, "Post", Route = "v1/job")] HttpRequest req,
ILogger logger)
{
...

或者,它只是不受支持?

谢谢。

将自定义类直接注入函数是不可能的,你仍然需要注入构造函数来实现你的想法。如果不选择注入构造函数,依赖项将不可用。编写其他代码是必要的。这是正确的方法:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#use-injected-dependencies

最新更新