使用动态基地址改装客户端

Refit Client using a dynamic base address

我正在使用 Refit 在 asp.net core 2.2 中使用 Typed Client 调用 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,是否有一种简单的方法可以动态 select 一个?

示例配置:

    "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);
    }
}

注入 ClientFactory 而不是客户端:

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);
    }
}