How to add a Startup class to Azure Functions
November 15, 2020 by Anuraj
Azure Functions Serverless
This blog post is about adding a Startup class to Azure Functions. So why we need a startup class for Azure function? For example if you’re building an Azure Function which talks to SQL Server Database or calling an external API, instead of creating the instance of Database Connection or HTTP Client directly in the code it is always recommended to us Dependency Injection, and inject the external dependencies to the functions. As Azure Functions running on top .NET Core, we can use the .NET Core dependency injection techniques.
Just now I created an HTTP Trigger Function.
In this example - I trying to use an InMemoryDatabase in an Azure function. Next I am creating a constructor which accepts the DbContext. Next I am removing the static modifier from the Run function as well.
Next we need to add the reference of the package - Microsoft.Azure.Functions.Extensions
, you can do it using the command - dotnet add package Microsoft.Azure.Functions.Extensions --version 1.1.0
.
Now we can add a class - Startup.cs with the following code.
In this above code I am injecting the DbContext and which is available in Function class. You can use this method to inject HttpClient
or any other dependencies you want to inject to the function code.
Happy Programming :)
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub