graphql-client icon indicating copy to clipboard operation
graphql-client copied to clipboard

Cannot access disposed object.

Open pkparadigm opened this issue 9 months ago • 1 comments
trafficstars

Code -

 // startup/registration DI code - 
services.AddHttpClient("GraphQLClient")
    .ConfigureHttpClient(client =>
    {
        client.BaseAddress = new Uri("https://api.example.com/graphql");
    });

services.AddScoped<GraphQLHttpClient>(sp =>
{
    var httpClientFactory = sp.GetRequiredService<IHttpClientFactory>();
    var httpClient = httpClientFactory.CreateClient("GraphQLClient");

    return new GraphQLHttpClient(
        new GraphQLHttpClientOptions { EndPoint = new Uri("https://api.example.com/graphql") },
        new SystemTextJsonSerializer(),
        httpClient
    );
});


public class Client
{
    private readonly GraphQLHttpClient _graphqlClient;

    public Client(GraphQLHttpClient graphqlClient)
    {
        this._graphqlClient = graphqlClient;
    }

    public async Task SomeMethod()
    {
        var request1 = new GraphQLRequest
        {
            Query = "{ students { id name } }"
        };

        var request2 = new GraphQLRequest
        {
            Query = "{ courses { id title } }"
        };

        var t = CallApi(request1);  
        var m = CallApi(request2);  // This throws Cannot access a disposed object Object name: System.Net.Http.StringContent exception

        await Task.WhenAll(t, m);   
    }

    private async Task CallApi(GraphQLRequest request)
    {
        var response = await _graphqlClient.SendQueryAsync<dynamic>(request); // exception thrown here 
        Console.WriteLine(response.Data);
    }
}

pkparadigm avatar Feb 11 '25 18:02 pkparadigm