Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

<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

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

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. 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. Please help.

like image 587
Casper Alant Avatar asked Aug 12 '19 07:08

Casper Alant


Video Answer


2 Answers

enter image description hereI've found that startup attribute stops working if the project has reference to user secrets id, in your NameOfYourProject.csproj try removing it.

<UserSecretsId>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</UserSecretsId>
like image 113
Karunakaran Avatar answered Sep 21 '22 15:09

Karunakaran


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/

like image 39
Napoleon Ike Jones Avatar answered Sep 25 '22 15:09

Napoleon Ike Jones