ABP.IO WEB應用程式框架 ICachedServiceProvider

筆記下 ICachedServiceProvider 與 HttpClient 的坑

結論

var httpClientFactory = _cachedServiceProvider.GetRequiredService<IHttpClientFactory>();
var httpClient = httpClientFactory.CreateClient(nameof(ITestService));
// ...
var response = await httpClient.PostAsJsonAsync("oauth/token", testRequest);

總之直接用 ICachedServiceProvider 取得 HttpClient 會吃不到 TypedHttpClient 的設定

這邊改用 ICachedServiceProvider取得 IHttpClientFactory再用 介面名稱 透過工廠模式取得

問題

var httpClient = _cachedServiceProvider.GetRequiredService<HttpClient>();
// ...
var response = await httpClient.PostAsJsonAsync("oauth/token", testRequest);

會報錯誤訊息

System.InvalidOperationException An invalid request URI was provided. 

Either the request URI must be an absolute URI or BaseAddress must be set. 

at System.Net.Http.HttpClient.PrepareRequestMessage(HttpRequestMessage request)

備註

ConfigureServices

private void ConfigureHttpClient(ServiceConfigurationContext context)
{
    var options = context.Services.ExecutePreConfiguredActions<TestOptions>();
    context.Services.AddHttpClient<ITestService, TestService>(httpClient =>
    {
        httpClient.BaseAddress = options.BaseAddress;
    });
}

參照

Dependency Injection | Documentation Center | ABP.IO

PS5