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

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

问题描述

给出一个文件->新建-> Azure Functions v2应用程序,我试图获取对 ILoggerFactory ILogger<的引用; T>

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 类中进行此操作

给出以下代码,将引发一个奇怪的异常:

Given the following code a weird exception is thrown:

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

,但以下情况除外:

< a href = https://i.stack.imgur.com/DkSUp.png rel = noreferrer>

 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.

推荐答案

看来,某些$ <$ c $必需的基础结构(例如 IFileLoggingStatusManager )在创建依赖项注入容器并尝试解析StartUp类中的记录器时,尚未设置c> HostFileLoggerProvider 。我认为您应该将日志记录延迟到应用程序完全启动之后。

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的启动代码,您会发现记录器已添加第一,然后< a href = https://github.com/Azure/azure-functions-host/blob/dev/src/WebJobs.Script/ScriptHostBuilderExtensions.cs#L111 rel = nofollow noreferrer>外部启动会被执行,最后是必填日志记录服务已添加。对于您的案件,这是错误的命令。

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天全站免登陆