9

我正在使用 Refit 在 asp.net core 2.2 中使用 Typed Client 调用 API,该 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 为时已晚。如果我有多个 BaseAddress,是否有一种简单的方法可以动态选择一个?

示例配置:

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

1 回答 1

7

注入 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);
    }
}
于 2019-10-29T17:00:20.833 回答