0

In my Xamarin app I get an exception on app startup on both Android and iOS.

"Cannot access a disposed object. Object name: 'MobileAuthenticatedStream'"

This seems to be happening after a background fetch has been run.

I am initializing my httpclientfactory like so

static void Init()
{
    var host = new HostBuilder()
    .ConfigureHostConfiguration(c =>
    {
        c.AddCommandLine(new string[] { $"ContentRoot={FileSystem.AppDataDirectory}" });
    })
    .ConfigureServices((c, x) =>
    {
        ConfigureServices(c, x);
    })
    .Build();
    ServiceProvider = host.Services;
}

static void ConfigureServices(HostBuilderContext ctx, IServiceCollection services)
{
    services.AddSingleton<Helpers.ClientService>();
    services.AddHttpClient("webClient", client =>
    {
        client.DefaultRequestHeaders.Authorization = GenerateAuthHeader();
    })
    .AddPolicyHandler(GetRetryPolicy());
}

Then getting the client for use like

public class ClientService
{
    IHttpClientFactory _httpClientFactory;
    public ClientService(IHttpClientFactory factory)
    {
        _httpClientFactory = factory;
    }

    public HttpClient GetClient()
    {
        return _httpClientFactory.CreateClient(App.ClientName);
    }
}
Helpers.ClientService service = App.ServiceProvider.GetService<Helpers.ClientService>();
HttpClient client = service.GetClient();
HttpResponseMessage response = await client.GetAsync(url);

On app start and resume I am re-running Init method.

Is this re-initializing the factory correctly, if not how should I implement this functionality

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Finlay Brown
  • 11
  • 1
  • 2
  • isn't this the same question you asked yesterday? – Jason Aug 24 '22 at 01:53
  • Do you know which line throw this exception? – Peter Csala Oct 09 '22 at 06:51
  • The exception is thrown on `HttpResponseMessage response = await client.GetAsync(url);` However i discovered the actual cause of this error and posted about it here https://stackoverflow.com/questions/73875522/prevent-background-fetch-starting-up-app-ui – Finlay Brown Oct 09 '22 at 21:08

0 Answers0