One of my favourite features of Azure Functions v2 and above is the ability to include a Startup class. Why is this cool you may ask? Well, it means that you can use .NET Core's built-in Dependency Injection (DI). This then means that project architecture can look remarkably like ASP.NET Core web apps. DI also makes testing easier as dependencies can be mocked. In this post, I'll show you how you can quickly add DI to an Azure Function.

Note: Azure Functions v3.0 became GA in January 2020. This means that you can now use .NET 3.1 and Node 12 in your Azure Functions. They still don't support the new System.Text.Json but that should come in time.

If you would like to see a full integration of Twilio APIs in a .NET Core application then checkout this free 5-part video series I created. It's separate from this blog post tutorial but will give you a full run down of many APIs at once.

Adding a Startup class to an Azure Function

Start with an existing Azure Function project or create a new project from the CLI/IDE. You can choose any type of Function but for ease, I would use an HTTP Trigger Function as it will be easier to test.

If you are using .NET Core 3.1, it's worth checking that your new function is set up correctly in the .csproj file.

The TargetFramework should be netcoreapp3.1

should be The AzureFunctionsVersion should be v3 and

should be and The Microsoft.NET.Sdk.Functions package should be version 3.0.3 or above

We will need to include a "Microsoft.Azure.Functions.Extensions" nuget package. You can add this using the package manager or you can add <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" /> to the <ItemGroup> node in the .csproj .

In the root of the project, add a new file called "Startup.cs". The default code in the new class should look similar to the code below, only with a namespace equal to the name of your project.