Search code examples
c#.nethotchocolate

Dependency Injection of services for GraphQL


I'm using NET5 webapi with HotChocolate package and am trying to inject a service. I've followed both standard and method based approach documented here however it doesn't work at all. All i get is the following message:

{
  "errors": [
    {
      "message": "Unexpected Execution Error",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "tests"
      ]
    }
  ],
  "data": {
    "tests": null
  }
}

My query:

query{
  tests {
    id
  }
}

My code currently reflects the method approach as documented.

In startup:

services
            .AddSingleton<ITestService, TestService>()
            .AddGraphQLServer()
            .AddDefaultTransactionScopeHandler()
            .AddQueryType<Queries>()
            .AddMutationType<Mutations>()
            .AddFiltering()
            .AddSorting()
            .AddProjections()
            .AddType<Test>();

The query setup:

        [UseProjection]
        [UseFiltering]
        [UseSorting]
        public IQueryable<Test> GetTests([Service] ITestService testService) => testService.GetTests();

My TestService:

private readonly IDbContextFactory<TestDbContext> contextFactory;

public TestService(IDbContextFactory<TestDbContext> contextFactory)
{
    this.contextFactory = contextFactory;
}

public IQueryable<Test> GetTests()
{
    using var context = contextFactory.CreateDbContext();

    return context.Test;
}

I'm sure I'm missing something simple to make this work.


Solution

  • Your DB Context is disposed. The using in GetTests is scoped for this method. On the end of this method the db context gets disposed and a Queryable is returned. Once the execution engine executes the Queryable, the exception is thrown

    Checkout the EF Core integration of HotChocolate: https://chillicream.com/docs/hotchocolate/integrations/entity-framework