ITypedHttpClientFactory<TClient> Interface

Definição

Uma abstração de fábrica para um componente que pode criar instâncias de cliente tipado com configuração personalizada para um determinado nome lógico.

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

Parâmetros de tipo

TClient

O tipo de cliente tipado a ser criado.

Exemplos

Este exemplo mostra o padrão básico para definir uma classe de cliente tipada.

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

Este exemplo mostra como consumir um cliente tipado de um middleware 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);
    });
}

Este exemplo mostra como consumir um cliente tipado de um controlador MVC ASP.NET Core.

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

Comentários

A ITypedHttpClientFactory<TClient> infraestrutura é compatível com a AddHttpClient<TClient>(IServiceCollection, String) funcionalidade e AddTypedClient<TClient>(IHttpClientBuilder) . Esse tipo raramente deve ser usado diretamente no código do aplicativo, use GetService(Type) em vez disso para recuperar clientes tipados.

Um padrão ITypedHttpClientFactory<TClient> pode ser registrado em um IServiceCollection chamando AddHttpClient(IServiceCollection). O padrão ITypedHttpClientFactory<TClient> será registrado na coleção de serviços como um serviço singleton open-generic.

O padrão ITypedHttpClientFactory<TClient> usa a ativação de tipo para criar instâncias de cliente tipada. Os tipos de cliente tipados não são recuperados diretamente do IServiceProvider. Para obter detalhes, consulte CreateInstance(IServiceProvider, Type, Object[]).

Métodos

CreateClient(HttpClient)

Cria um cliente tipado dado um HttpClient associado.

Aplica-se a