Search code examples
c#httpparametersbindingazure-functions

Cannot bind parameter, cause the parameter type is not supported by the binding (HttpTrigger of Azure Functions)


I have to migrate a part of a monolith to be able to run the migrated part independently, but i'm new in azure functions. Multiple HttpTriggers contain an a unsupported parameter type. (IMultiplierService)

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

I read online and understand that the string id is a reference to the {id:guid} in the route, but i could not find online what the purpose is of such an interface given as a parameter.

(IMultiplierService is a CRUD like interface. Contains method like 'GetById' or 'GetAll'.)

Can anyone explain how to support such a custom class as parameter input for the HttpTrigger Azure Function.

If you have questions or need more information. Go ahead.


Solution

  • The proper way to insert the crud like interface into the azure functions is to use dependency injection. You dont need to create static functions anymore. All you need to do is register the interface and its implementation in the startup class so that the azure functions runtime inject an instance of correct implementation of your interface. Consider following example of a azure function which uses a ISqlHelper interface. I write my non static function class as follows

    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}
    }
    

    And I register my instance of class which implements ISqlHelper in my startup class as

    [assembly: FunctionsStartup(typeof(MyFunction.Startup))]
    namepace MyFunction{
        public class Startup : FunctionsStartup
        {
            public override void Configure(IFunctionsHostBuilder builder)
            {
                builder.Services.AddTransient<ISqlHelper, SqlHelper>();
            }
        }
    }
    

    For more information on how to do it refer Dependency Injection in Azure Functions