Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot access disposed object. #666

Open
pkparadigm opened this issue Feb 11, 2025 · 1 comment
Open

Cannot access disposed object. #666

pkparadigm opened this issue Feb 11, 2025 · 1 comment

Comments

@pkparadigm
Copy link

pkparadigm commented Feb 11, 2025

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);
    }
}
@rose-a
Copy link
Collaborator

rose-a commented Feb 11, 2025

What's the reason for registering GraphQlHttpClient as scoped? It's meant to be used as a singleton instance per endpoint.

Please try if the problem goes away if you register GraphQlHttpClient as singleton.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants