Raymond Raymond

Dependency Injection and Use appsettings.json in .NET 5 Azure Functions

event 2021-08-24 visibility 4,853 comment 0 insights toc
more_vert
insights Stats
Dependency Injection and Use appsettings.json in .NET 5 Azure Functions

Option pattern is commonly used in .NET applications since the start of .NET Core. With .NET 5 isolated runtime for Azure Functions, we can now utilize the full features of .NET 5. This includes configuring using appsettings.json file and dependency injections. In previous .NET based Azure Functions, we usually use the following two mechanisms to create application settings:

  • Environment variables or on Azure, set the application configurations. 
  • For local development, we can use environment variables or local.settings.json. For the JSON configuration file, all key-values in Values node will be passed as environment variables. 

Now we can use appsettings.json as your other .NET 5 applications. This is extremely useful if you share same configuration files among different projects, for instance, sharing application settings between your Website and Azure Functions projects. 

Prerequisites

This tutorial builds on top of article Create Blob Triggered Azure Functions using .NET 5.

Now let's start to add appsettings.json and also an option class. 

Create appsettings.json

Create a JSON file named appsettings.json in the project with the following content:

{
  "AppConfig": {
    "StringValue": "This is a string configuration item",
    "BoolValue": true
  }
}

This creates a configuration node with two properties.

Change the properties of the file to ensure it will be copied to output folder when publishing:

20210824123649-image.png

Create an option class

Create an option class:

namespace AzureFunctionExample
{
    public class AppConfig
    {
        public string StringValue { get; set; }
        public bool BoolValue { get; set; }
    }
}

When deserializing from JSON file, this class will be instantiated. 

Dependency injection

Before we do go any further, let's change Function1 from a static function to an member function of the function class so that we can inject options.

infoThis article won't cover details about DI in .NET Azure Functions; please refer to the articles in the References section.

Now the function class looks like the following code snippet:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace AzureFunctionExample
{
    public class Function1
    {
        private readonly IOptions<AppConfig> appConfig;

        public Function1(IOptions<AppConfig> appConfig)
        {
            this.appConfig = appConfig;
        }

        [Function("Function1")]
        public void Run([BlobTrigger("blob-triggers/{name}", Connection = "AzureWebJobsStorage")] string myBlob, string name,
            FunctionContext context)
        {
            var logger = context.GetLogger("Function1");
            logger.LogInformation($"C# Blob trigger function Processed blob\n Name: {name} \n Data: {myBlob}");

            logger.LogCritical($"Application configurations: StringValue = {appConfig.Value?.StringValue}; BoolValue = {appConfig.Value?.BoolValue}");
        }
    }
}

The primary changes are:

  • The class is changed from static class to a class that can be instantiated.
  • The constructor has an injection for AppConfig.
  • In the function body, the configuration values are printed out.

Enable options and appsettings.json

Now we need to change Program.cs file to enable appsettings.json and also option injection.

Change the class file to the following content:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AzureFunctionExample
{
    public class Program
    {
        public static void Main()
        {
            var host = new HostBuilder()
                .ConfigureAppConfiguration(config =>
                {
                    config.AddJsonFile("appsettings.json", false, false).AddEnvironmentVariables().Build();
                })
                .ConfigureFunctionsWorkerDefaults()
                .ConfigureServices(services =>
                {
                    services.AddOptions<AppConfig>().Configure<IConfiguration>((settings, configuration) => configuration.GetSection("AppConfig").Bind(settings));
                })
                .Build();

            host.Run();
        }
    }
}

We used two additional methods:

  • ConfigureAppConfiguration: This function is used to enable JSON file settings as you would do with other type of .NET applications. You can further add support for environment specific configurations files by introducing an environment variable to indicate the additional JSON files like appsettings.Development.json or appsettings.Production.json
  • ConfigureServices: This is the standard dependency injections for services that are required by the function application. 

Run the application 

After all the changes you can now run the application again and the following screenshot shows the output:

20210824125532-image.png

You can add more application settings for your application.

IConfiguration class

You can also inject IConfiguration object into the your function class. Refer to IConfiguration Interface (Microsoft.Extensions.Configuration) for more details about how to utilize this root configuration class in .NET Core/.NET 5/6 applications.

References

Use dependency injection in .NET Azure Functions

Options pattern in ASP.NET Core

Quickstart for Azure App Configuration with Azure Functions

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts