Skip to content

Create Function Classes

Mika Berglund edited this page Aug 2, 2019 · 3 revisions

Create Function Classes

When you have wired up your application, it is time to create the functions in your function application. When you use the templates in Visual Studio 2019 (early August 2019), the function classes are always created as static classes.

Since we use dependency injection in our functions, the injected services are injected through the constructors of the class, so the classes cannot be static. If you create a function class with the templates in Visual Studio, be sure to change it to non-static. You can also create your function classes right from scratch.

Let's take the creation step by step. First, we create a class with a constructor that takes the dependencies we need in our function class.

public class ScheduledFunctions
{
    public ScheduledFunctions(AppSettingsRootConfig rootConfig)
    {
        this.AppConfig = rootConfig;
    }

    private readonly AppSettingsRootConfig AppConfig;
}

In the constructor, we store the dependency in a local class-level variable, so that we can use it in our functions. The following code is simply a demonstration of how we could use the dependency.

Note that the function is an instance method and not a static method, which is created when using the templates in Visual Studio 2019.

[FunctionName(nameof(Scheduled1))]
public async Task Scheduled1([TimerTrigger("*/10 * * * * *")]TimerInfo timer, ILogger logger)
{
    foreach(var container in this.AppConfig.MyApp.Containers)
    {
        logger.LogInformation($"Container: {container.Container}");
        await Task.Yield();
    }
}

The function does nothing special, and only enumerates the containers collection in our application settings, just for demonstration purposes.

This tutorial application contains two function classes, where functions are separated based on their types. You can of course distribute your functions across as many classes as you see fit, but remember that you can have multiple function methods in one class, so you don't need to create one class for each function.

The demo function classes are available in the code repository:

Clone this wiki locally