6

I'm using a couple of dataloaders that use injected query services (which in turn have dependencies on a DbContext). It looks something like this:

Field<ListGraphType<UserType>>(
  "Users",
  resolve: context =>
  {
    var loader = accessor.Context.GetOrAddBatchLoader<Guid, IEnumerable<User>>(
      "MyUserLoader",
      userQueryService.MyUserFunc);

    return loader.LoadAsync(context.Source.UserId);
  });
Field<ListGraphType<GroupType>>(
  "Groups",
  resolve: context =>
  {
    var loader = accessor.Context.GetOrAddBatchLoader<Guid, IEnumerable<Group>>(
      "MyGroupLoader",
      groupQueryService.MyGroupFunc);

    return loader.LoadAsync(context.Source.GroupId);
  });

When I run a nested query that concurrently uses both dataloaders I get an exception "A second operation started on this context before a previous asynchronous operation completed" because both dataloaders are using the same DbContext at the same time.

What's the best way to allow concurrent database access within the query without having to carefully manage DbContexts with ServiceLifeTime.Transient? Or can dataloader expose a way to know when to dispose of transient DbContexts?

x5657
  • 1,172
  • 2
  • 13
  • 26

2 Answers2

4

The problem will not be solved with switching from "Scoped" to "Transient" because Gql.Net field resolvers execute in parallel.

Based on your example, I'm expecting that your DbContext is constructor-injected into your "db service" classes (userQueryService and groupQueryService), and those were constructor-injected into your example GraphType class. So each of your db services have the exact same, scoped copy of your DbContext.

The solution is to lazy-resolve your DbContext.

The quick-and-dirty way is to use the "Service Locator" pattern.

You'd change your db-services to inject an IServiceScopeFactory. You then use that in your loader methods (MyUserFunc and MyGroupFunc) to create a scope and then resolve your DbContext. The problem with this approach ("Service Locator") is that the dependency on your DbContext is hidden inside of your class.

The better way (similar, but not "Service Locator")...

Use this relatively simple bit of code here on CodeReview.StackExchange to instead use an IServiceScopeFactory<T>. You get the lazy-resolving without doing "Service Locator"; your strongly-typed dependencies are declared up in the constructor.

Example

So pretend your userQueryService variable's class is like so:

MyDbContext _dbContext;
public UserQueryService(MyDbContext dbContext) => _dbContext = dbContext;

public async Task<IDictionary<Guid, IEnumerable<User>> MyUserFunc(IEnumerable<Guid> userIds)
{
    // code that uses _dbContext and returns the data...
}

Change it to this (again, using the IServiceScopeFactory<T>):

IServiceScopeFactory<MyDbContext> _dbFactory;
public UserQueryService(IServiceScopeFactory<MyDbContext> dbFactory) => _dbFactory = dbFactory;

public async Task<IDictionary<Guid, IEnumerable<User>> MyUserFunc(IEnumerable<Guid> userIds)
{
    using var scope = _dbFactory.CreateScope();
    var dbContext = scope.GetRequiredService();
    // code that uses dbContext and returns the data...
}

Now, when Gql.Net's resolvers (well, in this case, the data loader) ultimately execute this method, each use of your DbContext use their own scope and so they won't have execution problems like you have now.

Granger
  • 3,639
  • 4
  • 36
  • 34
  • Thanks for this detailed answer. I actually set the "db service" classes as transient too, so I don't have the scoped problem that you thought I might. This looks like a much better option though, when I get a chance to confirm it I'll report back! – x5657 Mar 17 '20 at 14:04
0

Graphql is a middleware registered as singleton.

Because dbcontext is used inside graphql, also if you use "AddDbContext" (that means "scoped") it isn't a real "scoped" because it is inside "singleton" main middleware!

So, context will be instanced only the first time!

You can solve in 2 methods:

1-register graphql as "scoped". But this means load all graphq types for each request-->it is slow!

2-use factory pattern to use context, and instance explicitly

Here a "real life" example of using graphql .net core

https://github.com/graphql-dotnet/graphql-dotnet/issues/576#issuecomment-626661695

Edit: here a recent implementation with scope at resolver level https://github.com/fenomeno83/graphql-dotnet-globalization-demo