Create a new implementation class called PostService.cs in the same folder like this:
usingSystem;usingMvvmCrossDemo.Core.Infrastructure.Extensions;usingMvvmCrossDemo.Core.Models;usingSystem.Collections.Generic;usingSystem.Net.Http;usingSystem.Threading.Tasks;namespaceMvvmCrossDemo.Core.Services{publicclassPostService:IPostService {privatereadonlyHttpClient _httpClient;privatestring apiUrl ="https://jsonplaceholder.typicode.com/";publicPostService() { _httpClient =newHttpClient(); }publicasyncTask<ResponseMessage<List<Post>>> GetPostList() {try {var response =await_httpClient.GetAsync($"{apiUrl}posts");if (response.StatusCode==System.Net.HttpStatusCode.OK) {var result =awaitresponse.ReadAsJsonAsync<List<Post>>();returnnewResponseMessage<List<Post>> { IsSuccess =true, Result = result }; }else {returnnewResponseMessage<List<Post>> { IsSuccess =false, // Show the detailed error message here according to the response. Message ="Errors" }; } }catch (Exception e) { // TODO: Log the exception here.returnnewResponseMessage<List<Post>> { IsSuccess =false, // Show the detailed error message here. Message ="Errors" }; } }publicasyncTask<ResponseMessage<Post>> GetPost(int id) {try {var response =await_httpClient.GetAsync($"{apiUrl}posts/{id}");if (response.StatusCode==System.Net.HttpStatusCode.OK) {var result =awaitresponse.ReadAsJsonAsync<Post>();returnnewResponseMessage<Post> { IsSuccess =true, Result = result }; }else {returnnewResponseMessage<Post> { IsSuccess =false, // Show the detailed error message here according to the response. Message ="Errors" }; } }catch (Exception e) { // TODO: Log the exception here.returnnewResponseMessage<Post> { IsSuccess =false, // Show the detailed error message here. Message ="Errors" }; } } }}
In the PostService class, I tried to handle all exceptions of the HTTP requests to avoid passing any unexpected result to the caller method. It is helpful to improve the stability of the App. We also need to use a logger to record the error message if you are developing a real App.
We do not need to worry about how to register the implement instance because MvvmCross will do everything by the code we mentioned before in the App.cs, as long as we follow the name convention of the services: