Introduction

As I was investigating registering strongly typed configuration the other day using the IOptions constructs it seemed to be the way to do it. However I’ve never been a fan of the options pattern for settings. It’s another “thing” to remember, it feels like it adds extra noise which isn’t needed and unless you use the monitor version you have to restart the application for updated settings values to be loaded anyway. So how can we register strongly typed configuration POCOs in Azure Functions?

IOptions Route

The basic way of registering the settings through the options pattern is as below.

builder.Services.AddOptions<MySettings>().Configure<IConfiguration>((settings, configure) =>
{
    configure.GetSection("MySettings").Bind(settings);
});

You have to call an additional Configure method after AddOptions to allow for manual configuration binding to the instance which is provided in the registration functionality. This uses the standard IConfiguration functionality to find the section of configuration you require and bind it into the instance of the settings you are working with.

Register all the things!

The issue I was finding when trying to register the strongly typed configuration is you can’t access the IConfiguration directly when registering the services. When you work in an ASP.NET Core 3.1+ application the IConfiguration can be injected into your startup class and be accessible but this doesn’t seem to be a concept in the DI structure of Azure Functions. If I’ve missed something please contact me on twitter details at the end of the post!

builder.Services.AddSingleton(sp =>
{
    var config = sp.GetRequiredService<IConfiguration>();
    return config.GetSection("MySettings").Get<MySettings>();
});

What you can do however is register a singleton of the settings POCO and configure it using the factory pattern. This gives you the ability to only be run once in the lifecycle of the application which is good. But also the overload of AddSingleton method has an overload which takes a Func<IServiceProvider, TService> delegate and that allows you access to the service provider instance to request the configuration when creating the instance of the POCO!

This can then be tided up to be a single line as below.

builder.Services.AddSingleton(sp => sp.GetRequiredService<IConfiguration>().GetSection("MySettings").Get<MySettings>());

Conclusion

In this short post we have looked at registering strongly typed settings pocos for Azure Functions without using the Options pattern.

Any questions/comments/tips then please get in contact on Twitter @WestDiscGolf as I am still learning and would love to hear about pros and cons of doing what I’ve done with Azure Functions.