私は Refit を使用して、現在、構成オプションから単一の BaseAddress を使用してブートストラップされている asp.net コア 2.2 の Typed Client を使用して API を呼び出しています。
services.AddRefitClient<IMyApi>()
.ConfigureHttpClient(c => { c.BaseAddress = new Uri(myApiOptions.BaseAddress);})
.ConfigurePrimaryHttpMessageHandler(() => NoSslValidationHandler)
.AddPolicyHandler(pollyOptions);
構成 json では、次のようになります。
"MyApiOptions": {
"BaseAddress": "https://server1.domain.com",
}
IMyApi インターフェースでは:
public IMyAPi interface {
[Get("/api/v1/question/")]
Task<IEnumerable<QuestionResponse>> GetQuestionsAsync([AliasAs("document_type")]string projectId);
}
現在のサービスの例:
public class MyProject {
private IMyApi _myApi;
public MyProject (IMyApi myApi) {
_myApi = myApi;
}
public Response DoSomething(string projectId) {
return _myApi.GetQuestionsAsync(projectId);
}
}
実行時のデータに基づいて、異なる BaseAddresses を使用する必要があります。私の理解では、Refit は HttpClient の単一のインスタンスを DI に追加するため、実行時に BaseAddresses を切り替えても、マルチスレッド アプリでは直接機能しません。今のところ、IMyApi のインスタンスを挿入してインターフェイス メソッド GetQuestionsAsync を呼び出すのは非常に簡単です。その時点で BaseAddress を設定するには遅すぎます。複数の BaseAddresses がある場合、1 つを動的に選択する簡単な方法はありますか?
構成例:
"MyApiOptions": {
"BaseAddresses": {
"BaseAddress1": "https://server1.domain.com",
"BaseAddress2": "https://server2.domain.com"
}
}
将来のサービスの例:
public class MyProject {
private IMyApi _myApi;
public MyProject (IMyApi myApi) {
_myApi = myApi;
}
public Response DoSomething(string projectId) {
string baseUrl = SomeOtherService.GetBaseUrlByProjectId(projectId);
return _myApi.UseBaseUrl(baseUrl).GetQuestionsAsync(projectId);
}
}
更新 受け入れられた回答に基づいて、次のようになりました。
public class RefitHttpClientFactory<T> : IRefitHttpClientFactory<T>
{
private readonly IHttpClientFactory _clientFactory;
public RefitHttpClientFactory(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public T CreateClient(string baseAddressKey)
{
var client = _clientFactory.CreateClient(baseAddressKey);
return RestService.For<T>(client);
}
}