.NET Core 2.2 Azure Function v2依赖关系注入

Ano*_*Dev 8 c# .net-core azure-functions

我在使用来注册单例时遇到问题Microsoft.Extensions.DependencyInjection。我创建了一个Startup类(肯定可以正常工作)并创建了一个ITestServicewith实现。

单例被注入到函数的构造函数中。最初,我对此实现没有问题,但是几天后,该函数由于无法解析而失败ITestService。我不知道为什么。

这是Startup

using Microsoft.Azure.WebJobs.Hosting;

[assembly: WebJobsStartup(typeof(Startup))]
namespace Test.Functions
{
    using System;

    using Microsoft.Azure.WebJobs;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;

    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("local.settings.json", true, true)
                .AddEnvironmentVariables()
                .Build();

            builder.Services.AddSingleton<ITestService>(new TestService("test string"));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是功能

public class TestFunction
{
    private readonly ITestService testService

    public TestFunction(ITestService testService)
    {
        this.testService = testService ?? throw new ArgumentNullException(nameof(testService));
    }

    [FunctionName(nameof(TestFunction))]
    public void Run([ServiceBusTrigger("test", Connection = "ServiceBusConnection")]Message message, ILogger log)
    {
        ////use test service here
    }
}
Run Code Online (Sandbox Code Playgroud)

当我调试启动并查看时,Services我看到实现类型是nullfor的ITestService,我认为这是为什么它无法解析的原因。就像我提到的那样,这完全可以工作几天。功能等的版本未更改。任何想法如何使它再次工作将不胜感激。

更新

我试图进一步简化此操作,并使用具有无参数构造函数的实现创建了另一个虚拟接口。我使用以下方法添加了它: builder.AddSingleton<ITestService2, TestService2>()

它显然将类型分配给实现类型,但是当需要将其注入到构造函数中时,它因相同的无法激活异常而失败。

Kir*_*kin 7

最新版本的函数主机中有一个回归,它破坏了依赖注入。

为了在Azure环境中解决此问题,可以通过将FUNCTIONS_EXTENSION_VERSION应用程序设置设置为来锁定功能主机的特定版本2.0.12342.0

如果使用azure-functions-core-toolsNPM软件包在本地运行功能主机,请确保使用2.4.419最新版本(2.4.498)会导致相同的问题。您可以使用以下命令明确安装:

npm i -g azure-functions-core-tools@2.4.419
Run Code Online (Sandbox Code Playgroud)

有关更多背景信息,请参见此GitHub问题