Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Implementing platform specific override method of custom client

$
0
0

I'm creating a custom API client to be used by my web (Blazor WebAssembly Standalone) and mobile (.NET MAUI) apps for connecting to my API. I have two questions below but first, here's an abbreviated version my code:

public class MyApiClient : IMyApiClient{   public async Task<User> GetUser()   {       // Check for Internet connection       if(!IsConnectedToInternet())          throw new Exception("No Internet connection!");       // Call API to get user info       ...   }   public virtual bool IsConnectedToInternet()   {      // Requires platform specific implementation      return false;   }}public interface IMyApiClient{   Task<User> GetUser();   bool IsConnectedToInternet();}

And in my Blazor app's Program.cs, I inject the HttpClient into MyApiClient this way:

...builder.services.AddHttpClient<MyApiClient>(client => client.BaseAddress = new Uri("https://www.example.com/api"));...

My questions are:

  1. Where do I create the override specific to a web app for IsConnectedToInternet() method? Doing this in Program.cs doesn't seem right.
  2. I'd like to use the IMyApiClient interface in Program.cs instead of the actual MyApiClient class. Where do I register the IMyApiClient interface and its implementation? Do I handle it the way I handle any local services and their interfaces in the Blazor app? For example: builder.services.AddSingleton<IMyApiClient, MyApiClient>(); in Program.cs? If so, is the order important e.g. do I need to inject the HttpClient after the registration?

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>