ITypedHttpClientFactory<TClient> インターフェイス

定義

特定の論理名のカスタム構成を使用して型指定されたクライアント インスタンスを作成できるコンポーネントのファクトリ抽象化。

generic <typename TClient>
public interface class ITypedHttpClientFactory
public interface ITypedHttpClientFactory<TClient>
type ITypedHttpClientFactory<'Client> = interface
Public Interface ITypedHttpClientFactory(Of TClient)

型パラメーター

TClient

作成する型指定されたクライアントの種類。

このサンプルでは、型指定されたクライアント クラスを定義するための基本的なパターンを示します。

class ExampleClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger _logger;

    // typed clients can use constructor injection to access additional services
    public ExampleClient(HttpClient httpClient, ILogger<ExampleClient> logger)
    {
        _httpClient = httpClient;
        _logger = logger;     
    }

    // typed clients can expose the HttpClient for application code to call directly
    public HttpClient HttpClient => _httpClient;

    // typed clients can also define methods that abstract usage of the HttpClient
    public async Task SendHelloRequest()
    {
        var response = await _httpClient.GetAsync("/helloworld");
        response.EnsureSuccessStatusCode();
    }
}

このサンプルでは、ASP.NET Core ミドルウェアから型指定されたクライアントを使用する方法を示します。

// in Startup.cs
public void Configure(IApplicationBuilder app, ExampleClient exampleClient)
{
    app.Run(async (context) =>
    {
        var response = await _exampleClient.GetAsync("/helloworld");
        await context.Response.WriteAsync("Remote server said: ");
        await response.Content.CopyToAsync(context.Response.Body);
    });
}

このサンプルでは、ASP.NET Core MVC コントローラーから型指定されたクライアントを使用する方法を示します。

// in Controllers/HomeController.cs
public class HomeController : ControllerBase(IApplicationBuilder app, ExampleClient exampleClient)
{
    private readonly ExampleClient _exampleClient;

    public HomeController(ExampleClient exampleClient)
    {
        _exampleClient = exampleClient;
    }

    public async Task<IActionResult> Index()
    {
        var response = await _exampleClient.GetAsync("/helloworld");
        var text = await response.Content.ReadAsStringAsync();
        return Content("Remote server said: " + text, "text/plain");
    };
}

注釈

ITypedHttpClientFactory<TClient>AddTypedClient<TClient>(IHttpClientBuilder) の機能をサポートするAddHttpClient<TClient>(IServiceCollection, String)インフラストラクチャです。 この型は、アプリケーション コードで直接使用されることはほとんどありません。代わりに を使用 GetService(Type) して、型指定されたクライアントを取得します。

既定値ITypedHttpClientFactory<TClient>は、 を呼び出AddHttpClient(IServiceCollection)すことによって にIServiceCollection登録できます。 既定値 ITypedHttpClientFactory<TClient> は、シングルトンのオープン ジェネリック サービスとしてサービス コレクションに登録されます。

既定 ITypedHttpClientFactory<TClient> では、型のアクティブ化を使用して型指定されたクライアント インスタンスを作成します。 型指定されたクライアントの種類は、 から IServiceProvider直接取得されません。 詳細については、CreateInstance(IServiceProvider, Type, Object[]) を参照してください。

メソッド

CreateClient(HttpClient)

関連付けられた HttpClient を指定して、型指定されたクライアントを作成します。

適用対象