我正在使用 Refit 在 asp.net core 2.2 中使用类型化客户端调用 API,该客户端当前使用配置选项中的单个 BaseAddress 进行引导:
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,是否有一种简单的方法来动态选择一个?
配置示例:
"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);
}
}
UPDATE根据已接受的答案,我最终得到以下结果:
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);
}
}