我正在尝试在Azure Function v3上注入IHttpClientFactory
服务,但是我不断收到以下错误消息,说解决服务失败。
我使用azure-functions-core-tools @ v3在本地运行Azure Function。
[2/14/2020 5:45:19 PM] Executed 'Foo' (Failed, Id=24489b3b-af99-417e-b175-443b76c241d5)
[2/14/2020 5:45:19 PM] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'MyFunction.Function.Foo'.
我有一个启动类,应该为IHttpClientFactory
注入服务。
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
namespace MyFunction
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();
}
}
}
下面是一个天蓝色的函数类,该类使用IHttpClientFactory
的注入服务来创建HTTP客户端并将GET请求发送到服务器。
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace MyFunction.Function
{
public class Foo
{
private readonly HttpClient httpClient;
public Scrape(IHttpClientFactory httpClientFactory)
{
httpClient = httpClientFactory.CreateClient();
}
[FunctionName("Foo")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
var result = await httpClient.GetAsync("https://google.com");
var data = await result.Content.ReadAsStringAsync();
return new OkObjectResult(data);
}
}
}
我想念什么吗?
答案 0 :(得分:2)
您的startup.cs
类似乎缺少它的程序集引用?
[assembly: FunctionsStartup(typeof(MyFunction.Startup))]
尝试将其添加到启动类中。将其添加到顶部的using
语句之后,任何名称空间声明之前。
此外,我看到的大多数示例都显示了在函数执行期间实际创建的客户端,而不是在默认构造函数中。
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace MyFunction.Function
{
public class Foo
{
private readonly HttpClient httpClient;
public Scrape(IHttpClientFactory httpClientFactory)
{
factory = httpClientFactory;
}
[FunctionName("Foo")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
HttpClient httpClient = factory.CreateClient();
var result = await httpClient.GetAsync("https://google.com");
var data = await result.Content.ReadAsStringAsync();
return new OkObjectResult(data);
}
}
}