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

[CommunityToolkit.Maui.Markup.Sample] Replace Refit + Polly with Microsoft.Extensions.Http.Polly and Refit.HttpClientFactory #112

Merged
merged 4 commits into from
Oct 3, 2022

Conversation

brminnick
Copy link
Collaborator

@brminnick brminnick commented Sep 14, 2022

To demonstrate best practices for .NET MAUI apps that utilize HttpClient, this PR replaces the following NuGet Packages:

  • Refit -> Refit.HttpClientFactory
  • Polly -> Microsoft.Extensions.Http.Polly

Because .NET MAUI supports dependency injection, we can leverage Refit.HttpClientFactory to easily implement REST API requests and Microsoft.Extensions.Http.Polly to add automatic error handling policies. In the updated code below, when HttpClient fails it will now automatically retry to connect to the URL 3 times using an exponential backoff of 2n seconds. This is ideal for flaky mobile internet connections where a user's device may switch cellular towers or lose a Wifi connection.

builder.Services.AddRefitClient<IHackerNewsApi>()
	.ConfigureHttpClient(client => client.BaseAddress = new Uri("https://hacker-news.firebaseio.com/v0"))
	.AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(3, sleepDurationProvider));

static TimeSpan sleepDurationProvider(int attemptNumber) => TimeSpan.FromSeconds(Math.Pow(2, attemptNumber));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant