'Change urlbase of HttpClient in Xamarin.Forms using Dependency Injection pattern

I'm developing an application with Xamarin.Forms for UWP and Android. Using the Dependency Injection pattern (DI), I register a service of HttpClient to manage connections with one back-end with configurable IP address in the app. In App.xaml.cs:

public App() {
        InitializeComponent();
        DependencyService.Register<System.Net.Http.HttpClient>();
        MainPage = new NavigationPage(new LoginPage());
}

In login page, I have a "Entry" component to edit the URL of my backend, due to my development requirements. In the LoginPage ViewModel, I get the service with

public HttpClient Http => DependencyService.Get<HttpClient>();

And them, I set the url base which the user introduces on the "Entry"

public async Task LoginMethod() {
      Http.BaseAddress = new Uri(TheIntroducedIP);
      /*Navigate to next pages and make some requests*/
}

This works, but the problem is if I come back to this LoginPage after doing some requests with HttpClient injected service and try to set the UrlBase again it throws an Exception:

System.InvalidOperationException: 'This instance has already started one or more requests. Properties can only be modified before sending the first request.'

Is there any way or different approach to reinject/restart the service so I can remap the urlbase?

Note: I wanted to keep using DI, avoiding creating different instances of HttpClient for each call using "using". In addition, I wanted to use the UrlBase property instead of entering the full path in each request.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source