简体   繁体   English

依赖注入在本地 Azure 函数中不起作用

[英]Dependency Injection not working in local Azure Function

Dependency Injection fails to initialize for me even though it seems to work for my team members.依赖注入无法为我初始化,即使它似乎对我的团队成员有效。 To test this, I've created a bare bones project that includes dependency injection ( using this guide ) and it still fails.为了对此进行测试,我创建了一个包含依赖项注入( 使用本指南)的裸机项目,但它仍然失败。

FunctionApp3.csproj FunctionApp3.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AzureFunctionsVersion>v2</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.29" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

Startup.cs启动文件

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using FunctionApp3;
[assembly: FunctionsStartup(typeof(Startup))]
namespace FunctionApp3
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton<IClass1, Class1>();
        }
    }
}

Class1.cs Class1.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace FunctionApp3
{
    public interface IClass1
    {
        string Name { get; set; }
    }
    class Class1 : IClass1
    {
        public string Name { get; set; }
    }
}

Function1.cs函数1.cs

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace FunctionApp3
{
    public class Function1
    {
        public Function1(IClass1 class1)
        {
        }

        [FunctionName("Function1")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {

            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            return (ActionResult)new OkObjectResult($"Hello, {name}");
        }
    }
}

The function starts up OK, with the following log:函数启动正常,日志如下:


                  %%%%%%
                 %%%%%%
            @   %%%%%%    @
          @@   %%%%%%      @@
       @@@    %%%%%%%%%%%    @@@
     @@      %%%%%%%%%%        @@
       @@         %%%%       @@
         @@      %%%       @@
           @@    %%      @@
                %%
                %

Azure Functions Core Tools (2.7.1505 Commit hash: eb8182995562240ca83dd0e0e3394586cf5fdfa3)
Function Runtime Version: 2.0.12590.0
[8/12/2019 6:38:30 AM] Building host: startup suppressed:False, configuration suppressed: False
[8/12/2019 6:38:31 AM] Initializing Host.
[8/12/2019 6:38:31 AM] Host initialization: ConsecutiveErrors=0, StartupCount=1
[8/12/2019 6:38:31 AM] LoggerFilterOptions
[8/12/2019 6:38:31 AM] {
[8/12/2019 6:38:31 AM]   "MinLevel": "None",
[8/12/2019 6:38:31 AM]   "Rules": [
[8/12/2019 6:38:31 AM]     {
[8/12/2019 6:38:31 AM]       "ProviderName": null,
[8/12/2019 6:38:31 AM]       "CategoryName": null,
[8/12/2019 6:38:31 AM]       "LogLevel": null,
[8/12/2019 6:38:31 AM]       "Filter": "<AddFilter>b__0"
[8/12/2019 6:38:31 AM]     },
[8/12/2019 6:38:31 AM]     {
[8/12/2019 6:38:31 AM]       "ProviderName": "Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.SystemLoggerProvider",
[8/12/2019 6:38:31 AM]       "CategoryName": null,
[8/12/2019 6:38:31 AM]       "LogLevel": "None",
[8/12/2019 6:38:31 AM]       "Filter": null
[8/12/2019 6:38:31 AM]     },
[8/12/2019 6:38:31 AM]     {
[8/12/2019 6:38:31 AM]       "ProviderName": "Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.SystemLoggerProvider",
[8/12/2019 6:38:31 AM]       "CategoryName": null,
[8/12/2019 6:38:31 AM]       "LogLevel": null,
[8/12/2019 6:38:31 AM]       "Filter": "<AddFilter>b__0"
[8/12/2019 6:38:31 AM]     }
[8/12/2019 6:38:31 AM]   ]
[8/12/2019 6:38:31 AM] }
[8/12/2019 6:38:31 AM] FunctionResultAggregatorOptions
[8/12/2019 6:38:31 AM] {
[8/12/2019 6:38:31 AM]   "BatchSize": 1000,
[8/12/2019 6:38:31 AM]   "FlushTimeout": "00:00:30",
[8/12/2019 6:38:31 AM]   "IsEnabled": true
[8/12/2019 6:38:31 AM] }
[8/12/2019 6:38:31 AM] SingletonOptions
[8/12/2019 6:38:31 AM] {
[8/12/2019 6:38:31 AM]   "LockPeriod": "00:00:15",
[8/12/2019 6:38:31 AM]   "ListenerLockPeriod": "00:00:15",
[8/12/2019 6:38:31 AM]   "LockAcquisitionTimeout": "10675199.02:48:05.4775807",
[8/12/2019 6:38:31 AM]   "LockAcquisitionPollingInterval": "00:00:05",
[8/12/2019 6:38:31 AM]   "ListenerLockRecoveryPollingInterval": "00:01:00"
[8/12/2019 6:38:31 AM] }
[8/12/2019 6:38:31 AM] Starting JobHost
[8/12/2019 6:38:31 AM] Starting Host (HostId=hatch0000299-876386545, InstanceId=59950e48-2bcb-4bdc-b803-555c91e0f068, Version=2.0.12590.0, ProcessId=31024, AppDomainId=1, InDebugMode=False, InDiagnosticMode=False, FunctionsExtensionVersion=)
[8/12/2019 6:38:31 AM] Loading functions metadata
[8/12/2019 6:38:32 AM] 1 functions loaded
[8/12/2019 6:38:32 AM] Generating 1 job function(s)
[8/12/2019 6:38:32 AM] Found the following functions:
[8/12/2019 6:38:32 AM] FunctionApp3.Function1.Run
[8/12/2019 6:38:32 AM]
[8/12/2019 6:38:32 AM] Host initialized (718ms)
[8/12/2019 6:38:32 AM] Host started (739ms)
[8/12/2019 6:38:32 AM] Job host started
Hosting environment: Production
Content root path: C:\Users\alan90960\source\repos\FunctionApp3\FunctionApp3\bin\Debug\netcoreapp2.2
Now listening on: http://0.0.0.0:7071
Application started. Press Ctrl+C to shut down.

Http Functions:

        Function1: [GET,POST] http://localhost:7071/api/Function1

[8/12/2019 6:38:37 AM] Host lock lease acquired by instance ID '000000000000000000000000BC4F0480'.

But then fails when I trigger the function:但是当我触发函数时失败了:

[8/12/2019 6:38:39 AM] Executing HTTP request: {
[8/12/2019 6:38:39 AM]   "requestId": "9ba771f2-0d4d-4773-9d83-eef9ccb849c3",
[8/12/2019 6:38:39 AM]   "method": "GET",
[8/12/2019 6:38:39 AM]   "uri": "/api/Function1"
[8/12/2019 6:38:39 AM] }
[8/12/2019 6:38:40 AM] Executed 'Function1' (Failed, Id=64a341ca-b9ea-40f8-b158-fbef015d7da6)
[8/12/2019 6:38:40 AM] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'FunctionApp3.IClass1' while attempting to activate 'FunctionApp3.Function1'.
[8/12/2019 6:38:40 AM] An unhandled host error has occurred.
[8/12/2019 6:38:40 AM] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'FunctionApp3.IClass1' while attempting to activate 'FunctionApp3.Function1'.
[8/12/2019 6:38:40 AM] Executed HTTP request: {
[8/12/2019 6:38:40 AM]   "requestId": "9ba771f2-0d4d-4773-9d83-eef9ccb849c3",
[8/12/2019 6:38:40 AM]   "method": "GET",
[8/12/2019 6:38:41 AM]   "uri": "/api/Function1",
[8/12/2019 6:38:41 AM]   "identities": [
[8/12/2019 6:38:41 AM]     {
[8/12/2019 6:38:41 AM]       "type": "WebJobsAuthLevel",
[8/12/2019 6:38:41 AM]       "level": "Admin"
[8/12/2019 6:38:41 AM]     }
[8/12/2019 6:38:41 AM]   ],
[8/12/2019 6:38:41 AM]   "status": 500,
[8/12/2019 6:38:41 AM]   "duration": 1592
[8/12/2019 6:38:41 AM] }

I've tried setting a breakpoint in Startup.cs and it doesn't get hit.我试过在 Startup.cs 中设置断点,但没有成功。 If I don't use dependency injections, a breakpoint does get hit in the function.如果我不使用依赖注入,断点确实会在函数中被击中。

I've tried using netcoreapp2.2 and netcoreapp2.1 and also repaired Visual Studio.我试过使用 netcoreapp2.2 和 netcoreapp2.1 并修复了 Visual Studio。 Please help.请帮忙。

在此处输入图片说明 I've found that startup attribute stops working if the project has reference to user secrets id, in your NameOfYourProject.csproj try removing it.我发现如果项目引用了用户机密 ID,则启动属性将停止工作,请在您的NameOfYourProject.csproj尝试将其删除。

<UserSecretsId>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</UserSecretsId>

For using .NET Core Version 2.2 you need to reference the nuget package for Microsoft.NET.Sdk.Functions v1.0.29.要使用 .NET Core 2.2 版,您需要参考 Microsoft.NET.Sdk.Functions v1.0.29 的 nuget 包。

Version v1.0.26 was not hitting the break point for me.版本 v1.0.26 没有达到我的断点。

You need to use the fully qualified name of the startup class in the assembly attribute.您需要在程序集属性中使用启动类的完全限定名称。

[assembly: FunctionsStartup(typeof(FunctionsApp3.Startup))]

https://ikethe.dev/azure-functions-adds-dependency-injection/ https://ikethe.dev/azure-functions-adds-dependency-injection/

I got this problem after upgrading my Azure Functions Core Tools and after upgrading the nuget packages ie Microsoft.NET.Sdk.Functions and Microsoft.Azure.Functions.Extensions.在升级我的 Azure Functions Core Tools 并升级了 nuget 包(即 Microsoft.NET.Sdk.Functions 和 Microsoft.Azure.Functions.Extensions)后,我遇到了这个问题。

I resolved it by deleting the obj and bin folders on the project and recompiling.我通过删除项目上的 obj 和 bin 文件夹并重新编译来解决它。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM