Function App with Dependency Injection and Custom Configuration in C# and .Net Core
Today, we are going to discuss , how to inject dependencies in Function App host during the startup and will also use custom configuration file to read Application Settings and write logs and Telemetry data in Azure Application Insights.
- Azure Account and Subscription, if you don’t have, please use Microsoft Learn Sandboxes.
- VS 2019
Nuget Packages Required:
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" /><PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.13" /><PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.13" />
Please remember one thing, Microsoft.Azure.Functions.Extensions 1.1.0 does not support other packages > “3.1.13”, if you use the latest one, it will give an exception while loading the startup.
- Go to VS2019.
- Create a Function App project with Http Trigger.
- Add above mentioned nuget packages.
- Add a new .cs file named Startup.cs and copy paste the below code, I have explained the significance of each part parts and why we are using it and what can be done.
5. By default, function app class will be static and the function app Run method will also be static and also ILogger will be passed as parameter in Run method and you need to make some changes as shown in the below snippet.
Please remember that, by default hosts inject ILogger and ILoggerFactory services into the constructors. so we don’t need to add those services until or unless we have our own custom logging provider, then we need to configure the services in startup accordingly.
5. You can add a new .json file named appsettings.json, containing your environment settings like below,
6. Then you need to change the .csproj file a bit in order to copy the appsettings.json to the output folder during the build. You can add below mentioned lines under <ItemGroup></ItemGroup>
7. Please create an Application Insights Instance in Azure and pass the Instrumentation key in appsettings.json .
8. Clean and rebuild your solution and run it.
9. it will start sending the telemetry data and logs to your Application Insight Instance. It will look like below,
Please follow Microsoft Documentation for any doubts and clarifications on the same.
Please click here to see Microsoft Documentation on this topic,https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection
Stay tuned and follow me for Azure Related Updates, and also please comment Any Queries or Any topic you need to know related to Azure, we both can help each other in the journey to cloud.