This post refers specifically to Azure Function V2.
If you want to write automated tests for Azure Functions methods and want to be able to control dependencies (e.g. to inject mock versions of things) you can set up dependency injection.
One way to do this is to install the AzureFunctions.Autofac NuGet package into your functions project.
Once installed, this package allows you to inject dependencies into your function methods at runtime.
Step 1: Create DI Mappings
The first step (after package installation) is to create a class that configures the dependencies. As an example suppose there was a function method that needed to make use of an implementation of an IInvestementAllocator. The following class can be added to the functions project:
using Autofac;
using AzureFunctions.Autofac.Configuration;
namespace InvestFunctionApp
{
public class DIConfig
{
public DIConfig(string functionName)
{
DependencyInjection.Initialize(builder =>
{
builder.RegisterType<NaiveInvestementAllocator>().As<IInvestementAllocator>(); // Naive
}, functionName);
}
}
}
In the preceding code, a constructor is defined that receives the name of the function that’s being injected into. Inside the constructor, types can be registered for dependency injection. In the preceding code the IInvestementAllocator interface is being mapped to the concrete class NaiveInvestementAllocator.
Step 2: Decorate Function Method Parameters
Now the DI registrations have been configured, the registered types can be injected in function methods. To do this the [Inject] attribute is applied to one or more parameters as the following code demonstrates:
[FunctionName("CalculatePortfolioAllocation")]
public static void Run(
[QueueTrigger("deposit-requests")]DepositRequest depositRequest,
[Inject] IInvestementAllocator investementAllocator,
ILogger log)
{
log.LogInformation($"C# Queue trigger function processed: {depositRequest}");
InvestementAllocation r = investementAllocator.Calculate(depositRequest.Amount, depositRequest.Investor);
}
Notice in the preceding code the [Inject] attribute is applied to the IInvestementAllocator investementAllocator parameter. This IInvestementAllocator is the same interface that was registered earlier in the DIConfig class.
Step 3: Select DI Configuration
The final step to make all this work is to add an attribute to the class that contains the function method (that uses [Inject]). The attribute used is the DependencyInjectionConfig attribute that takes the type containing the DI configuration as a parameter, for example: [DependencyInjectionConfig(typeof(DIConfig))]
The full function code is as follows:
using AzureFunctions.Autofac;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
namespace InvestFunctionApp
{
[DependencyInjectionConfig(typeof(DIConfig))]
public static class CalculatePortfolioAllocation
{
[FunctionName("CalculatePortfolioAllocation")]
public static void Run(
[QueueTrigger("deposit-requests")]DepositRequest depositRequest,
[Inject] IInvestementAllocator investementAllocator,
ILogger log)
{
log.LogInformation($"C# Queue trigger function processed: {depositRequest}");
InvestementAllocation r = investementAllocator.Calculate(depositRequest.Amount, depositRequest.Investor);
}
}
}
At runtime, when the CalculatePortfolioAllocation runs, an instance of an NaiveInvestementAllocator will be supplied to the function.
The library also supports features such as named dependencies and multiple DI configurations, to read more check out GitHub.
If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.
SHARE: