Monday, April 8, 2024

Middleware in .NET Isolated Azure Functions

In this post, let's have a look at Middleware in .NET Isolated Azure Functions. .NET Isolated functions supports middleware registration, following a similar model as in ASP.NET Core. With middleware, we can inject logic into the invocation pipeline, and before and after functions execute.

The ConfigureFunctionsWorkerDefaults method has an overload that we can register middleware as follows.
IHost host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults((context, builder) =>
    {
        // Register Middleware

        // This middleware is applied to all functions
        builder.UseMiddleware<MyCustomMiddleware>();

        // This middleware is only applied when running integration tests
        IConfiguration configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>();
        bool isRunningIntegrationTests = configuration.GetValue<bool>("IsRunningIntegrationTests");
         builder.UseWhen<IntegrationTestsFunctionMiddleware>((context) => isRunningIntegrationTests);
    })
    .Build();
To implement a middleware, you need to implement the interface IFunctionsWorkerMiddleware
internal sealed class IntegrationTestsFunctionMiddleware : IFunctionsWorkerMiddleware
{
    internal static class FunctionBindingTypes
    {
        public const string ServiceBus = "serviceBus";
    }

    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        // If the function has a service bus output binding, short-circuit the execution of the function
        if (context.FunctionDefinition.OutputBindings.Values.Any(a => a.Type == FunctionBindingTypes.ServiceBus))
        {
            return;
        }

        await next(context);
    }
}
Above IntegrationTestsFunctionMiddleware short-circuits the execution of the function if the function has a serviceBus output binding.

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment