httpClientFactory- services AddHttpClient
Mia Lopez
I am having a problem following this guide:
this is my configureservices
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }this is my page
public class IndexModel : PageModel { private readonly IHttpClientFactory httpClientFactory; public IList<Blog> Blog { get; set; } public IndexModel(IHttpClientFactory httpClientFactory) { this.httpClientFactory = httpClientFactory; } public async Task OnGetAsync() { } }I am receiving following error when browsing to my page:
InvalidOperationException: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'WebApplication1.Pages.Blogs.IndexModel'.am I missing something? Thanks for any advice
regards,
foo
42 Answers
the HttpClientFactory is not injected, AddHttpClient injects HttpClient.
try:
public class SampleService : ISampleService
{ private readonly HttpClient _httpClient; public SampleService(HttpClient httpClient) { _httpClient = httpClient; }
} I think that you have to create HttpClient:
private readonly HttpClient httpClient;
public IndexModel(IHttpClientFactory httpClientFactory)
{ this.httpClient = httpClientFactory.CreateClient();
}