【问题标题】:Inject DI instance directly in function method (Azure Functions)直接在函数方法中注入 DI 实例(Azure Functions)
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多