尝试在 Azure 函数中使用依赖注入时出现奇怪的异常 [英] Weird exception when trying to use Dependency Injection in an Azure Function

查看:27
本文介绍了尝试在 Azure 函数中使用依赖注入时出现奇怪的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定文件->新建->Azure Functions v2 应用程序,我正在尝试获取对 ILoggerFactoryILogger 的引用.

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

我在 StartUp.cs 类中执行此操作,该类在函数应用启动时运行.

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>();         

以下例外:

 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

这是怎么回事?

完整的测试存储库/代码可以在在 GitHub 上找到.

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

推荐答案

HostFileLoggerProvider 所需的一些基础设施(例如 IFileLoggingStatusManager)似乎尚未在当您创建依赖项注入容器并尝试解析 StartUp 类中的记录器时.我认为您应该将日志记录延迟到应用程序完全启动之后.

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.

如果您查看 WebJobs 的启动代码,您会看到记录器已添加首先,然后是执行外部启动,最后是 所需的日志服务.对于您的案例,哪个顺序是错误的.

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.

这篇关于尝试在 Azure 函数中使用依赖注入时出现奇怪的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆