Weird exception when trying to use Dependency Inje

2020-02-14 03:16发布

问题:

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:

 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.

回答1:

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.