Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add named and typed clients section #32456

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions aspnetcore/fundamentals/http-requests.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ There are several ways `IHttpClientFactory` can be used in an app:
* [Basic usage](#basic-usage)
* [Named clients](#named-clients)
* [Typed clients](#typed-clients)
* [Named and typed clients](#named-and-typed-clients)
* [Generated clients](#generated-clients)

The best approach depends upon the app's requirements.
Expand Down Expand Up @@ -114,6 +115,38 @@ The configuration for a typed client can also be specified during its registrati

:::code language="csharp" source="http-requests/samples/6.x/HttpRequestsSample/Snippets/Program.cs" id="snippet_AddHttpClientTypedInline":::

### Named and typed clients

Named clients and typed clients have their own strengths and weaknesses. There is a way to combine these two client types to get the best of both worlds.

The primary use case is the following: You want to register the exact same type client multiple times but with different settings (different base address, timeout, and credentials for example).
peter-csala marked this conversation as resolved.
Show resolved Hide resolved

The registration of the named and typed clients:

:::code language="csharp" source="http-requests/samples/6.x/HttpRequestsSample/Snippets/Program.cs" id="snippet_AddHttpClientTypedInline":::

In the preceding code:

* Two `GitHubService` typed clients were registered with different timeouts.
* The `Timeout` was used as an example for the sake of simplicity, in a real-world scenario the two underlying `HttpClient` could be setup in a very different way.

The usage of the named and typed clients:

:::code language="csharp" source="http-requests/samples/6.x/HttpRequestsSample/Pages/Consumption/NamedAndTypedClient.cshtml.cs" id="snippet_Class" highlight="4,6-7,19-20,23,25-26":::

In the preceding code:

* The `NamedAndTypedClientModel`'s constructor received two parameters: an `IHttpClientFactory` and an `ITypedHttpClientFactory<GitHubService>`.
* The former type resides inside the `System.Net.Http` namespaces whereas the latter type inside the `Microsoft.Extensions.Http`.
* The `ITypedHttpClientFactory`'s type parameter was the implementation class (in the preceding example the `GitHubService`).
* Even if you have an abstraction (like `IGitHubService` interface) as well, the type parameter must be the implementation type.
* If you accidentally use the abstraction (`GitHubService`) then it will throw an `InvalidOperationException` when you call its `CreateClient`.
* Inside the `OnGet` a `Quick` named and typed client will be created for the happy path.
* First the `IHttpClientFactory` is used to create a `Quick` named client.
* Then the `ITypedHttpClientFactory`'s `CreateClient` is called with the previous named client to wrap it into a named and typed client.
* If the request times out (takes longer than 1 second) then the `HttpClient` throws a `TaskCanceledException` with a `TimeoutException` inner.
* In this case, a `LatencyTolerant` named and typed client will be created.

### Generated clients

`IHttpClientFactory` can be used in combination with third-party libraries such as [Refit](https://github.com/reactiveui/refit). Refit is a REST library for .NET. It converts REST APIs into live interfaces. Call `AddRefitClient` to generate a dynamic implementation of an interface, which uses `HttpClient` to make the external HTTP calls.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@
<li><a asp-page="./Basic">Basic usage</a></li>
<li><a asp-page="./NamedClient">Named client</a></li>
<li><a asp-page="./TypedClient">Typed client</a></li>
<li><a asp-page="./NamedAndTypedClient">Named and typed client</a></li>
</ul>
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
@page
@model HttpRequestsSample.Pages.TypedClientModel

@{
ViewData["Title"] = "Consumption - Named and typed";
}

<h1>Consumption patterns - Named and typed client</h1>

@await Component.InvokeAsync("GitHubBranches", new { gitHubBranches = Model.GitHubBranches })
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using HttpRequestsSample.GitHub;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Http;

namespace HttpRequestsSample.Pages;

// <snippet_Class>
public class NamedAndTypedClientModel : PageModel
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ITypedHttpClientFactory<GitHubService> _gitHubServiceFactory;

public NamedAndTypedClientModel(IHttpClientFactory httpClientFactory,
ITypedHttpClientFactory<GitHubService> gitHubServiceFactory)
{
_httpClientFactory = httpClientFactory;
_gitHubServiceFactory = gitHubServiceFactory;
}

public IEnumerable<GitHubBranch>? GitHubBranches { get; set; }

public async Task OnGet()
{
try
{
var quickClient = _httpClientFactory.CreateClient("Quick");
var gitHubService = _gitHubServiceFactory.CreateClient(quickClient);
GitHubBranches = await gitHubService.GetAspNetCoreDocsBranchesAsync();
}
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
var tolerantClient = _httpClientFactory.CreateClient("LatencyTolerant");
peter-csala marked this conversation as resolved.
Show resolved Hide resolved
var gitHubService = _gitHubServiceFactory.CreateClient(tolerantClient);
GitHubBranches = await gitHubService.GetAspNetCoreDocsBranchesAsync();
}
}
}
// </snippet_Class>
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@
builder.Services.AddHttpClient<GitHubService>();
// </snippet_AddHttpClientTyped>

// <snippet_AddHttpClientNamedAndTyped>
builder.Services.AddHttpClient<GitHubService>("Quick", httpClient =>
{
httpClient.Timeout = TimeSpan.FromSeconds(1);
});
builder.Services.AddHttpClient<GitHubService>("LatencyTolerant", httpClient =>
{
httpClient.Timeout = TimeSpan.FromSeconds(10);
});
// </snippet_AddHttpClientNamedAndTyped>

// <snippet_AddHttpClientPollyWaitAndRetry>
builder.Services.AddHttpClient("PollyWaitAndRetry")
.AddTransientHttpErrorPolicy(policyBuilder =>
Expand Down
Loading