/serverless

The Ultimate Guide to Fixing Azure Function problems.

In the century of serverless apps and architecture, we create and work with many serverless apps. Today let’s see a simple problem that occurs while developing Azure Functions.

Let’s imagine you are creating a simple Function app with some services and configurations that is injected using DI => Dependency Injection.

A pure startup class looks like this, where you use the IConfiguration to inject the values from any settings.json file you have.

[assembly: FunctionsStartup(typeof(AzureFunctionApp.Startup))]
namespace AzureFunctionApp
{
  public class Startup : FunctionsStartup
	{
		public override void Configure(IFunctionsHostBuilder builder)
		{
			var config = new ConfigurationBuilder()
						  .AddJsonFile("local.settings.json",optional: true,
                           reloadOnChange: true)
						 .AddEnvironmentVariables()
						 .Build();

			builder.Services.TryAddSingleton<IConfiguration>(config);

		}
	}
}

Whenever you create an Azure Function it is created as static. So make it non-static .

Now let’s look at the HTTP Azure function Function.cs. A simple Http triggered function with a constructor injected parameter.

public class MyAzureFunc
	{
		private readonly IConfiguration _config;
		public MyAzureFunc(IConfiguration configuration)
		{
			_config = configuration;
		}
		[FunctionName("Function1")]
		public static async Task<IActionResult> Run(
				[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
				ILogger log)
		{
			log.LogInformation("C# HTTP trigger function processed a request.");

		}
	}

Now, if you run the function, the constructor won’t get hit even if you put a breakpoint on it. Today one of my co-worker faced this issue. Since I had already arrived across this issue, I was able to help my friend quickly.

What is the Issue

  • If you take a deep look at the function code example, you might notice the [FunctionName("Function1")] attribute.
  • Now this is different from the actual function class name MyAzureFunc
  • This is why the breakpoint won’t get hit nor the constructor get’s populated.
  • I think this is because since we are using the Microsoft.Azure.Functions.Extensions.DependencyInjection package in the startup to inject services, it tries to match the name of the function with the name of the class.

The solution

Keep the name of the class and the name inside the [FunctionName("MyAzureFunc")] attribute same.

Conclusion

I thought this might take some time to find out researching github and stackoverflow threads. I have’nt seen any blogs for this. I hope this might help future people facing this issue.

Happy Coding!! Keep following for more blogs :)

HariHaran

HariHaran

Full Stack Developer

Read More