Dependency Injection with Azure Functions and FunctionsStartup

Dependency Injection with Azure Functions and FunctionsStartup

Azure Functions provides a very lean way to execute code serverless. So lean, in fact, that there is no dependency injection by default.

With the help of NuGet and the Azure Function Extensions, however, Dependency Injection can be easily retrofitted, as the pattern itself is naturally supported.

Required NuGet Packages

First of all you need those NuGet Packages

Code

All the magic is done by FunctionsStartup.

With the help of FunctionsStartup we can configure our services in a startup class, e.g. from ASP.NET Core.

In principle, it is even possible to outsource the entire Statup content and share it with other .NET Core environments. The signatures and the behavior is identical to all other startup configurations. It is fully compatible.

 1[assembly: FunctionsStartup(typeof(MyCompany.MyApp.Startup))]
 2namespace MyCompany.MyApp
 3{
 4    public class Startup : FunctionsStartup
 5    {
 6        public override void Configure(IFunctionsHostBuilder builder)
 7        {
 8            // Http Client
 9            builder.Services.AddHttpClient();
10
11            // Analaytic Options
12            builder.Services.Configure<AnalyticsOptions>(options =>
13                {
14                    options.Url = Environment.GetEnvironmentVariable("ANALYTICS_SERVICE_API");
15                });
16            builder.Services.AddScoped<IAnalyticsService, NoiseAnalyticsService>();
17
18            // Notification
19            builder.Services.AddScoped<INotificationProvider, NotificationProvider>();
20
21            // Engine
22            builder.Services.AddMediatR(typeof(DeviceProcessingEngine));
23        }
24    }
25}

In the Azure Function Trigger, the respective instance of a service or another class can now simply be specified via the constructor as usual, so that it can be used in the class.

 1public class IoTHubMessageProcessor
 2{
 3    private readonly IMediator _mediator;
 4
 5    public IoTHubMessageProcessor(IMediator mediator)
 6    {
 7        _mediator = mediator;
 8    }
 9
10    [FunctionName("iot-hub-message")]
11    public async Task Run(
12        [EventHubTrigger("device-sensor-events", 
13            Connection = "AZURE_EVENT_HUB_DTSENSOR_INGEST_CONNECTIONSTRING")] EventData[] eventData,
14        ILogger log)
15    {
16        if (eventData is null)
17        {
18            log.LogWarning($"Received sensor event but no messages were passed.");
19            return;
20        }

Comments

Twitter Facebook LinkedIn WhatsApp