我正在使用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);
}
}
我现在需要在运行时基于数据使用不同的BaseAddress。我的理解是,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);
}
}
public class ClientFactory
{
public IMyApi CreateClient(string url) => RestService.For<IMyApi>(url);
}
public class MyProject {
private ClientFactory _factory;
public MyProject (ClientFactory factory) {
_factory = factory;
}
public Response DoSomething(string projectId) {
string baseUrl = SomeOtherService.GetBaseUrlByProjectId(projectId);
var client = _factory.CreateClient(baseUrl);
return client.GetQuestionsAsync(projectId);
}
}