简体   繁体   English

依赖注入无法解析在 Azure 中运行的 .NET Core Function App 中的类型的服务

[英]Dependency Injection unable to resolve service for type in .NET Core Function App running in Azure

Summary概括

I've been following the Microsoft guidance Use dependency injection in .NET Azure Functions to introduce some Dependency Injection (DI) into an Azure Function that our team is creating.我一直在遵循 Microsoft 指南Use dependency injection in .NET Azure Functions将一些依赖注入 (DI) 引入我们团队正在创建的 Azure 函数中。 When I run locally in Visual Studio 2017 and invoke the function using Fiddler or Postman everything works - I can debug hitting breakpoints and the service being provided via the DI setup are working correctly.当我在 Visual Studio 2017 中本地运行并使用 Fiddler 或 Postman 调用该函数时,一切正常 - 我可以调试命中断点,并且通过 DI 设置提供的服务正常工作。 When we deploy the same function into Azure, however, we get the following exception:但是,当我们将相同的功能部署到 Azure 中时,会出现以下异常:

Unable to resolve service for type 'MyLibrary.ITelemetryClient' while attempting to activate 'MyFunctionApp.GetRemoteSystemsByFeature'.尝试激活“MyFunctionApp.GetRemoteSystemsByFeature”时无法解析“MyLibrary.ITelemetryClient”类型的服务。

Details细节

I have a library assembly (.NET Standard 2.0) that exposes an interface, ITelemetryClient , and a default implementation, ApplicationInsightsTelemetryClient .我有一个库程序集 (.NET Standard 2.0),它公开了一个接口ITelemetryClient和一个默认实现ApplicationInsightsTelemetryClient They're pretty straightforward bits of code - I don't think the implementation of these are important to the issue, so I'll skip them for now.它们是非常简单的代码——我认为这些代码的实现对这个问题并不重要,所以我现在将跳过它们。

In the solution that defines our function app (.NET Core 2.2) I've made sure the right NuGet packages are installed:在定义我们的函数应用(.NET Core 2.2)的解决方案中,我确保安装了正确的 NuGet 包:

  • Microsoft.Azure.Functions.Extensions v1.0.0 Microsoft.Azure.Functions.Extensions v1.0.0
  • Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator v1.1.1 Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator v1.1.1
  • Microsoft.NET.Sdk.Functions v1.0.28 Microsoft.NET.Sdk.Functions v1.0.28

I have created Startup which inherits from FunctionsStartup :我创建了继承自FunctionsStartupStartup

using System;
using System.Runtime.CompilerServices;
using MyLibrary;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(MyFunctionApp.Startup))]
[assembly: InternalsVisibleTo("MyFunctionApp.Tests")]

namespace MyFunctionApp
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton<MyLibrary.ITelemetryClient, MyLibrary.ApplicationInsightsTelemetryClient>();
        }
    }
}

I then give my function a constructor that asks for the MyLibrary.ITelemetryClient :然后我给我的函数一个构造函数,它要求MyLibrary.ITelemetryClient

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using MyLibrary;
using MyRepository;
using MyService;

namespace MyFunctionApp
{
    public class GetRemoteSystemsByFeature
    {
        private readonly MyLibrary.ITelemetryClient _telemetryClient;

        public GetRemoteSystemsByFeature(MyLibrary.ITelemetryClient telemetryClient)
        {
            _telemetryClient = telemetryClient;
        }

        // snip - the rest shouldn't matter for this question
    }
}

So I think I've done everything right.所以我认为我做的一切都是正确的。 And as I said when I debug locally the whole thing works and the correct ITelemetryClient implementation is used and successfully does its thing.正如我所说,当我在本地调试时,整个事情都正常工作,并且使用了正确的ITelemetryClient实现并成功地完成了它的工作。

When it gets deployed into Azure, though, we get the error quoted above.但是,当它被部署到 Azure 中时,我们会得到上面引用的错误。 The stack trace for that exception doesn't mention any of our code:该异常的堆栈跟踪没有提到我们的任何代码:

System.InvalidOperationException:
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService (Microsoft.Extensions.DependencyInjection.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
   at lambda_method (Anonymously Hosted DynamicMethods Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null)
   at Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstance (Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\DefaultJobActivator.csMicrosoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: 42)
   at Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstance (Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\DefaultJobActivator.csMicrosoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: 32)
   at Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory`1+<>c__DisplayClass1_1.<.ctor>b__0 (Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\ActivatorInstanceFactory.csMicrosoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: 20)
   at Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory`1.Create (Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\ActivatorInstanceFactory.csMicrosoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: 26)
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.CreateInstance (Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.csMicrosoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: 44)
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor+ParameterHelper.Initialize (Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.csMicrosoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: 845)
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor+<TryExecuteAsyncCore>d__16.MoveNext (Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35Microsoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.csMicrosoft.Azure.WebJobs.Host, Version=3.0.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35: 116)

Any ideas?有任何想法吗?

Update更新

It was requested I share the contents of the extensions.json file:有人要求我分享extensions.json文件的内容:

{
  "extensions":[
    { "name": "Startup", "typeName":"MyFunctionApp.Startup, MyFunctionApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"}
  ]
}

After uninstalling the Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator package from the MyFunctionApp and redeploying the dependency injection errors stopped and things started working correctly.MyFunctionApp卸载Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator包并重新部署依赖项注入后,错误停止并且事情开始正常工作。 Thanks to anyone who offered their insights, especially to Katy Shimizu .感谢任何提供见解的人,尤其是Katy Shimizu

You need to add Microsoft.ApplicationInsights.AspNetCore to your project and add this to your Startup.cs class:您需要将Microsoft.ApplicationInsights.AspNetCore添加到您的项目中,并将其添加到您的Startup.cs类中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry(Configuration);
    ...
}

Ok after a lot of messing about, i just updated my Microsoft.NET.sdk.Functions to 1.0.28 and im now getting an application error so its got past the DI error.好吧,经过一番折腾,我刚刚将我的 Microsoft.NET.sdk.Functions 更新为 1.0.28,我现在收到了一个应用程序错误,因此它通过了 DI 错误。 Try that and let me know how you get on.试试看,让我知道你是怎么过的。

Ok i see you are on 1.0.28, im using .netcore 2.1 if that helps?好的,我看到您使用的是 1.0.28,如果有帮助,我正在使用 .netcore 2.1?

Ran into this exact problem, trying to deploy an Azure Function CosmosDB ChangeFeedListener.遇到了这个确切的问题,尝试部署 Azure Function CosmosDB ChangeFeedListener。 Locally ran fine, once deployed it couldn't find the dependencies to inject in Startup.本地运行良好,一旦部署它就找不到要在 Startup 中注入的依赖项。

There is a long history of DI issues with Azure Functions. Azure Functions 的 DI 问题由来已久。 Went down a long rabbit hole for this one.为这个走了一个长长的兔子洞。

Problem : /publish/bin/extensions.json was being generated like this:问题/publish/bin/extensions.json是这样生成的:

{
   "extensions":
    [
     { "name": "CosmosDB", 
       "typeName":"Microsoft.Azure.WebJobs.Extensions.CosmosDB.CosmosDBWebJobsStartup, 
        Microsoft.Azure.WebJobs.Extensions.CosmosDB, Version=3.0.7.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35"
     }
   ]
}

Instead of this:而不是这个:

{
   "extensions":
    [
     { "name": "Startup", "typeName":"<ProjectNamespace>.Startup, <ProjectNamespace>, 
        Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"},
     { "name": "CosmosDB", 
       "typeName":"Microsoft.Azure.WebJobs.Extensions.CosmosDB.CosmosDBWebJobsStartup, 
        Microsoft.Azure.WebJobs.Extensions.CosmosDB, Version=3.0.7.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35"
     }
   ]
}

Solution :解决方案

Remove Microsoft.NET.Sdk.Functions

Azure Function .csproj: Azure 函数 .csproj:

<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>

就我而言,我错过了 [程序集:FunctionsStartup(typeof(MyFunctionApp.Startup))]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 .NET Core 依赖注入; 尝试激活服务时无法解析“System.String”类型的服务 - .NET Core Dependency Injection; Unable to resolve service for type 'System.String' while attempting to activate Service ASP.NET 核心依赖注入错误 - 尝试激活“服务”时无法解析“存储库”类型的服务 - ASP.NET Core Dependency Injection error - Unable to resolve service for type “Repository” while attempting to activate “Service” .NET 核心依赖注入错误:“无法解析“AspNetCoreWebAPI.Data.IBookRepository”类型的服务” - .NET Core dependency injection error : "Unable to resolve service for type 'AspNetCoreWebAPI.Data.IBookRepository'" Net Core 2控制台应用程序-DI&#39;无法解析类型的服务...&#39; - Net Core 2 Console App - DI 'Unable to resolve service for type…' NET Core依赖注入——根据依赖解析服务或配置 class - NET Core dependency injection - resolve service or configuration based on dependent class System.InvalidOperationException:无法解析类型的服务 - 依赖注入 - System.InvalidOperationException: Unable to resolve service for type - Dependency Injection InvalidOperationException:无法解析.Net Core类型的服务 - InvalidOperationException: Unable to resolve service for type .Net Core .NET Core 2.2 Azure功能v2依赖注入 - .NET Core 2.2 Azure Function v2 Dependency Injection Net Core - 无法解决依赖关系 - Net Core - unable to resolve dependency .NET Core WebAPI 依赖注入解析 null - .NET Core WebAPI dependency injection resolve null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM