I receive an error when I try to use a typed client for HttpClient as documented here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2
Here is my setup:
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
services.AddHttpClient<IPStackService>(c =>
{
c.BaseAddress = new Uri(Configuration["IPStackURL"]);
});
services.AddHttpContextAccessor();
services.AddTransient<IIPStackService, IPStackService>();
}
Controller:
[Route("api/[controller]")]
[ApiController]
public class RenderController : ControllerBase
{
private IConfiguration _configuration;
private readonly ILogger _logger;
private IIPStackService _ipMetaDataService;
public RenderController(IConfiguration configuration,
ILogger<RenderController> logger,
IIPStackService ipStackService)
{
_configuration = configuration;
_ipStackService = ipStackService;
_logger = logger;
}
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[Produces("text/plain")]
public async Task<ActionResult> GetAsync(string hostId, string clientUtc)
{
var ip = Common.ResolveIPAddress(HttpContext);
var ipMetaData = await _ipStackService.GetByIPAsync(ip, _configuration["AccessKey"]);
// removed for clarity
return allowed ? Ok(true) : Ok(null);
}
}
Service:
public class IPStackService : IIPStackService
{
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
public IPStackService(ILogger<IPStackService> logger, HttpClient client)
{
_logger = logger;
_httpClient = client;
}
public async Task<IPMetaDataModel> GetByIPAsync(string ip, string accessKey)
{
var ipMetaData = new IPMetaDataModel();
var response = await _httpClient.GetAsync($"/{ip}?access_key={accessKey}");
response.EnsureSuccessStatusCode();
// removed for clarity
return ipMetaData;
}
}
Error received:
An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'WebScreen.Gate.Services.IPStackService'. Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)
How do I setup typed clients properly for HttpClient?
The Activator for
IPStackService
(code reflection) cannot find theHttpClient
in the DI collection, that's why you got the exception (specifically for theservices.AddTransient<IIPStackService, IPStackService>()
).BTW, you a added the service
IPStackService
twice in your DI collection:services.AddHttpClient<IPStackService>(...);
.services.AddTransient<IIPStackService, IPStackService>()
;You only need one, and since you are using typed client you can solve your issue by removing the second one and keep the first, and alter the first one a tiny bit by adding the contract to the implementation, as follow:
The
AddHttpClient
will take care of binding theHttpClinet
to your service.And in case you want to use
services.AddTransient<IIPStackService, IPStackService>();
instead ofservices.AddHttpClient
, then you need to add theHttpClinet
to your DI Collection as: