Search code examples
azuredependency-injectionazure-functionsihttpclientfactory

FileNotFoundException when starting Azure Function project which uses dependency injection of IHttpClientFactory locally


I am new to Azure Function and trying to create a test project of Azure Function which uses dependency injection of IHttpClientFactory. But I have been stuck with FileNotFoundException when starting the project locally from Visual Studio.

The test project is Azure Function v4 under .NET 6.0 and runs on Visual Studio 17.5.0. It is pretty straightforward and based on the instruction of Use dependency injection in .NET Azure Functions. I checked similar cases in SO but could not make this project run so far. Is there any solution or workaround for this?

Project file

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.3" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

local.settings.json

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet"
    }
}

Startup class

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

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

namespace AzureFunctionTest;

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddHttpClient();

        builder.Services.AddSingleton<MyService>((s) =>
        {
            return new MyService();
        });
    }
}

Azure Function class

using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;

namespace AzureFunctionTest;

public class Function1
{
    private readonly HttpClient _client;
    private readonly IMyService _service;

    public Function1(IHttpClientFactory httpClientFactory, IMyService service)
    {
        _client = httpClientFactory.CreateClient();
        _service = service;
    }

    [FunctionName("Function1")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        var response = await _client.GetAsync("https://www.microsoft.com");
        var message = $"{_service.GetMessage()}: {response.Headers.Date}";

        return new OkObjectResult(message);
    }
}

You can find the test project's repository at emoacht/AzureFunctionTest

The exception is thrown at ConfigureStartup method of WebJobsBuilderExtensions and it says could not load file or assembly Microsoft.Extensions.Http. enter image description here

StackTrace of the exception

System.IO.FileNotFoundException
  HResult=0x80070002
  Message=Could not load file or assembly 'Microsoft.Extensions.Http, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
  Source=AzureFunctionTest
  StackTrace:
   at AzureFunctionTest.Startup.Configure(IFunctionsHostBuilder builder) in C:\Users\EM\Documents\Visual Studio 2022\Projects\AzureFunctionTest\AzureFunctionTest\Startup.cs:line 18
   at Microsoft.Azure.WebJobs.WebJobsBuilderExtensions.ConfigureStartup(IWebJobsStartup startup, WebJobsBuilderContext context, IWebJobsBuilder builder) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsBuilderExtensions.cs:line 162
   at Microsoft.Azure.WebJobs.WebJobsBuilderExtensions.ConfigureAndLogUserConfiguredServices(IWebJobsStartup startup, WebJobsBuilderContext context, IWebJobsBuilder builder, ILoggerFactory loggerFactory) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsBuilderExtensions.cs:line 130
   at Microsoft.Azure.WebJobs.WebJobsBuilderExtensions.UseWebJobsStartup(IWebJobsBuilder builder, Type startupType, WebJobsBuilderContext context, ILoggerFactory loggerFactory) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsBuilderExtensions.cs:line 115
   at Microsoft.Azure.WebJobs.WebJobsBuilderExtensions.UseExternalStartup(IWebJobsBuilder builder, IWebJobsStartupTypeLocator startupTypeLocator, WebJobsBuilderContext context, ILoggerFactory loggerFactory) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsBuilderExtensions.cs:line 213
   at Microsoft.Azure.WebJobs.Script.ScriptHostBuilderExtensions.<>c__DisplayClass7_0.<AddScriptHostCore>b__1(HostBuilderContext context, IWebJobsBuilder webJobsBuilder)
   at Microsoft.Extensions.Hosting.WebJobsHostBuilderExtensions.<>c__DisplayClass5_0.<ConfigureWebJobs>b__1(HostBuilderContext context, IServiceCollection services) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsHostBuilderExtensions.cs:line 54
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at Microsoft.Azure.WebJobs.Script.WebHost.WebJobsScriptHostService.<UnsynchronizedStartHostAsync>d__52.MoveNext()

Output when the exception is thrown

Exception thrown: 'System.IO.FileNotFoundException' in Microsoft.Azure.WebJobs.Host.dll
An exception of type 'System.IO.FileNotFoundException' occurred in Microsoft.Azure.WebJobs.Host.dll but was not handled in user code
Could not load file or assembly 'Microsoft.Extensions.Http, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.

Output when opening the project

Azure Functions Core Tools are up to date.
AzureFunctionTest: Azurite Blob service is starting at http://127.0.0.1:10000
AzureFunctionTest: Azurite Blob service is successfully listening at http://127.0.0.1:10000
AzureFunctionTest: Azurite Queue service is starting at http://127.0.0.1:10001
AzureFunctionTest: Azurite Queue service is successfully listening at http://127.0.0.1:10001
AzureFunctionTest: Azurite Table service is starting at http://127.0.0.1:10002
AzureFunctionTest: Azurite Table service is successfully listening at http://127.0.0.1:10002

Solution

  • I tried to reproduce the issue by cloning your code to my environment and I was getting the same error:

    enter image description here

    Check if the below fix helps you to resolve the issue:

    I have degraded the version of Microsoft.Extensions.Http from 7.0.0 to 6.0.0 and it worked fine for me. enter image description here

    Dependencies:

    <ItemGroup>
        <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
        <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
        <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
        <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.3" />
      </ItemGroup>