I know I'll get crucified for asking this question that has been asked a million times before and I promise you that I've looked at most of those questions/answers but I'm still a bit stuck.
This is a .NET Standard 2.0 class library supporting an ASP.NET Core 6 API.
In my Program.cs I create a named HttpClient like this:
builder.Services.AddHttpClient("XYZ_Api_Client", config =>
{
var url = "https://example.com/api";
config.BaseAddress = new Uri(url);
});
I have a custom client that will use this HttpClient and I create a singleton MyCustomClient in Program.cs so that my repositories can use it. The code is below. This is where I'm stuck as I'm not sure how to pass my named HttpClient into MyCustomClient.
builder.Services.AddSingleton(new MyCustomClient(???)); // I think I need to pass the HttpClient to my CustomClient here but not sure how
And my CustomClient needs to use this HttpClient named XYZ_Api_Client to do its job:
public class MyCustomClient
{
private readonly HttpClient _client;
public MyCustomClient(HttpClient client)
{
_client = client;
}
public async Task<bool> DoSomething()
{
var result = await _client.GetAsync();
return result;
}
}
So I'm not sure how I can pass this named HttpClient into MyCustomClient in the Program.cs.
You can directly inject the
IHttpClientFactoryin you class, and then assign the namedHttpClientto a property.Register the factory and your custom client:
And then in you class:
Or, you can pass the named instance when registering
MyCustomClientRegister the factory and your custom client:
And then in you class:
You can also do this:
What
AddHttpClient<TClient>(IServiceCollection)does isYou can find the full documentation here.