【发布时间】:2020-05-29 08:42:37
【问题描述】:
我想像这样在 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)
{
...
或者,它只是不支持?
谢谢。
【问题讨论】:
-
这能回答你的问题吗? DI in Azure Functions
-
感谢您的回复。我重新提出了这个问题,我想知道如何避免另外写一些东西......
-
尝试在 IStartJobHandler 之前指定 [FromServices]。它对 aspnet 核心应用程序有效,不确定它是否也适用于函数。
-
其他选项是编写您自己的自定义绑定。 github.com/Azure/azure-webjobs-sdk/wiki/… 老实说,如果这仅由一项服务使用,我认为这是不值得的。正在创建一个实现
IStartJobHandler和选项的类的实例。 (我有 IStartJobHandler 的可用信息)
标签: c# azure dependency-injection azure-functions