Add example showing usage with Autofac ContainerBuilder
Is your feature request related to a problem? Please describe.
Currently, we can easily register Refit using HttpClientFactory but it is much harder to do with Autofac.
I'm registering Refit using:
builder.Register(c =>
{
var cfg = c.Resolve<IConfiguration>();
var apiUrl = cfg["UsersApi_Url"];
_logger.Debug( $"[UsersModule::Load -> Register] Users API URL: {apiUrl}");
var httpClient = new HttpClient()
{
BaseAddress = new Uri(apiUrl)
};
return RestService.For<IUsersApi>(httpClient);
}).As<IUsersApi>().InstancePerDependency();
Describe the solution you'd like
Ideally, there should be an extension method for ContainerBuilder that will allow registering services without that much code.
Describe alternatives you've considered
Describe suggestions on how to achieve the feature
Additional context
Ideally, we should be able to register individual services and be able to specify configuration per service (for example base address)
Maybe API like this:
//ctx - IComponentContext
//c - HttpClient
builder.AddRefitClient<ICompaniesApi>((ctx, c) =>
{
var configuration = ctx.Resolve<IConfiguration>();
var apiUrl = configuration["CompaniesApi_Url"];
c.BaseAddress = new Uri(apiUrl);
});
I haven't used Autofac before, but I'm wondering is it not possible to use HttpClientFactory with Autofac? It's bad practice to new up instances of HttpClient directly as this can lead to socket exhaustion, so it wouldn't be right to put code into Refit that could potentially destabilize people's applications. HttpClientFactory was created to solve this problem, and hence it should be used to manage the lifecycle of HttpClient objects in the system.
There's a pretty good article written quite a number of years ago now that outlines the problem: https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
ASP.NET Monsters
I’ve been using HttpClient wrong for years and it finally came back to bite me. My site was unstable and my clients furious, with a simple fix performance improved greatly and the instability disapear