Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird exception when trying to use Dependency Injection in an Azure Function

Given a File->New->Azure Functions v2 App, I'm trying to get a reference to either an ILoggerFactory or an ILogger<T>.

I'm doing this in the StartUp.cs class which is ran on the function app start.

Given the following code a weird exception is thrown:

var serviceProvider = builder.Services.BuildServiceProvider();
var loggerFactory = serviceProvider.GetService<ILoggerFactory>();         

with the following exception:

enter image description here

 A host error has occurred
[27/02/2019 8:21:22 AM] Microsoft.Extensions.DependencyInjection: Unable to resolve service for type 'Microsoft.Azure.WebJobs.Script.IFileLoggingStatusManager' while attempting to activate 'Microsoft.Azure.WebJobs.Script.Diagnostics.HostFileLoggerProvider'.
Value cannot be null.
Parameter name: provider

What is going on?

The full test repo/code can be found here on GitHub.

like image 329
Pure.Krome Avatar asked Feb 27 '19 08:02

Pure.Krome


People also ask

What is dependency injection in Azure functions?

Azure Functions supports the dependency injection (DI) software design pattern, which is a technique to achieve Inversion of Control (IoC) between classes and their dependencies. Dependency injection in Azure Functions is built on the . NET Core Dependency Injection features.

How much memory does an azure function have?

For function apps in a Premium plan or an App Service plan, you can map a custom domain using either a CNAME or an A record. Guaranteed for up to 60 minutes. Workers are roles that host customer apps. Workers are available in three fixed sizes: One vCPU/3.5 GB RAM; Two vCPU/7 GB RAM; Four vCPU/14 GB RAM.


1 Answers

It seems that some infrastructure (e.g. IFileLoggingStatusManager) necessary for HostFileLoggerProvider is not set up yet at the time you are creating the dependency injection container and attempt to resolve the logger in the StartUp class. I think you should delay logging until after the application has fully started.

If you look at the startup code of WebJobs you'll see that the logger gets added first, after that the external startup gets executed and finally the required logging services gets added. Which is the wrong order for your case.

like image 87
Henk Mollema Avatar answered Nov 12 '22 22:11

Henk Mollema