首页 > 解决方案 > 无法绑定参数,导致绑定不支持参数类型(Azure Functions的HttpTrigger)

问题描述

我必须迁移单体的一部分才能独立运行迁移的部分,但我是天蓝色函数的新手。多个 HttpTrigger 包含不受支持的参数类型。( IMultiplierService)

public static async Task<IActionResult> GetMultiplier( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "multipliers/{id:guid}")] HttpRequest req, string id, IMultiplierService multiplierService){ ... }

我在网上阅读并了解这string id是对路线中的引用{id:guid},但我无法在网上找到作为参数给出的这种接口的目的是什么。

IMultiplierService是一个类似于 CRUD 的接口。包含像“GetById”或“GetAll”这样的方法。)

谁能解释如何支持这样一个自定义类作为 HttpTrigger Azure 函数的参数输入。

如果您有疑问或需要更多信息。前进。

标签: c#httpparametersbindingazure-functions

解决方案


将类似 crud 的接口插入到 azure 函数中的正确方法是使用依赖注入。您不再需要创建静态函数。您需要做的就是在启动类中注册接口及其实现,以便 azure 函数运行时注入接口正确实现的实例。考虑以下使用 ISqlHelper 接口的 azure 函数示例。我编写我的非静态函数类如下

public class NotifyMember
{
    private readonly ISqlHelper _sqlHelper;

    public NotifyMember(ISqlHelper sqlHelper)
    {
        _sqlHelper = sqlHelper ?? throw new ArgumentNullException(nameof(sqlHelper));

    }

    [FunctionName(nameof(NotifyMember))]
    public async Task Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "multipliers/{id:guid}")] HttpRequest req,
      string id, ILogger logger)
    {//Perform function work here}
}

我将在我的启动类中实现 ISqlHelper 的类实例注册为

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddTransient<ISqlHelper, SqlHelper>();
    }
}

有关如何执行此操作的更多信息,请参阅Azure Functions 中的依赖注入


推荐阅读