Once I moved my podcast website over to ASP.NET Core 2.1 I additionally began utilizing HttpClientFactory and wrote up my expertise. It is a good clear option to centralize each settings and coverage in your HttpClients, particularly should you’re utilizing loads of them to speak to loads of small providers.

Final 12 months I explored Refit, an computerized type-safe REST library for .NET Customary. It makes it tremendous straightforward to only declare the form of a consumer and its related REST API with a C# interface:

public interface IGitHubApi

after which ask for an HttpClient that speaks that API’s form, then name it. Fabulous.

var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");


var octocat = await gitHubApi.GetUser("octocat");

However! What does Refit seem like and the way does it work in an HttpClientFactory-enabled world? Refit has lately been up to date with top notch assist for ASP.NET Core 2.1’s HttpClientFactory with the Refit.HttpClientFactory package deal.

Since you will wish to centralize all of your HttpClient configuration in your ConfigureServices technique in Startup, Refit provides a pleasant extension technique hanging off of Companies.

You add a RefitClient of a sort, then add no matter different IHttpClientBuilder strategies you need afterwards:

providers.AddRefitClient<IWebApi>()

.ConfigureHttpClient(c => c.BaseAddress = new Uri("https://api.instance.com"));
// Add extra IHttpClientBuilder chained strategies as required right here:
// .AddHttpMessageHandler<MyHandler>()
// .SetHandlerLifetime(TimeSpan.FromMinutes(2));

In fact, then you’ll be able to simply have your HttpClient robotically created and handed into the constructor. You may see on this pattern from their GitHub that you simply get an IWebAPI (that’s, no matter kind you need, like my IGitHubApi) and simply go to city with a strongly typed interfaces of an HttpClient with autocomplete.

public class HomeController : Controller

Refit is simple to make use of, and even higher with ASP.NET Core 2.1. Go get Refit and check out it as we speak!

* Sturdy picture by Lucyb_22 used below Inventive Commons from Flickr


Sponsor: Take a look at dotMemory Unit, a free unit testing framework for combating all types of reminiscence points in your code. Prolong your unit testing with the performance of a reminiscence profiler.


© 2018 Scott Hanselman. All rights reserved.

     



Supply hyperlink

LEAVE A REPLY

Please enter your comment!
Please enter your name here