Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 10 Remote Data

Prebuilt Libraries

I first recommend that you investigate whether the web service provider also provides a client library to make the consumption easier. Quite often providers supply a library, especially when there is a layer of authentication required. There are no official client libraries for the Open

Weather API; however, there are a number of NuGet packages that provide some support for using the API.

Code Generation Libraries

If no client library is available, you can look to using an auto generation package to reduce the amount of code you need to write. Refit is a fantastic package for this purpose. It allows you to define an interface representing the web service call and then Refit will do the rest.

So why didn’t I just start here? In a new project, you probably would do so, but I always strongly feel that you need to gain an understanding of what packages like Refit are doing before you really start to use them. This can be invaluable when things go wrong and you have to debug exactly what and why things are going wrong!

Adding the Refit NuGet Package

Let’s go ahead and add the Refit.HttpClientFactory NuGet package and then take a look at how to use it.

•\

Right-click the WidgetBoard solution.

•\

Select Manage NuGet Packages.

•\

Search for Refit.HttpClientFactory.

•\

Select the correct package.

•\

Click Add Package.

327

Chapter 10 Remote Data

Now that you have the NuGet package installed, you can use it. Open your IWeatherForecastService.cs file and make the following modifications shown in bold:

using Refit;

namespace WidgetBoard.Communications;

public interface IWeatherForecastService

{

[Get("/onecall?lat={latitude}&lon={longitude}&units=metric&

exclude=minutely,hourly,daily,alerts&appid=APIKEY")]

Task<Forecast> GetForecast(double latitude, double longitude);

}

The fantastic part of the above code is that you do not need to write the implementation. Refit uses source code generators to do it for you! In fact, it means you can delete your WeatherForecastService class as it is no longer required.

The final change you are required to make is to change how you register the IWeatherForecastService with your MauiAppBuilder in the

MauiProgram.cs file. Open it up and make the following changes. First, add the using statement.

using Refit;

Then replace

builder.Services.AddSingleton<IWeatherForecastService,

WeatherForecastService>();

with

328