Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle concurrent DbContext access in dataloaders / GraphQL nested queries?

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?

like image 591
x5657 Avatar asked Nov 15 '19 08:11

x5657


1 Answers

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.

like image 182
Granger Avatar answered Nov 05 '22 16:11

Granger