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

孤者浪人 提交于 2020-05-09 05:41:52

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/58873249/how-to-handle-concurrent-dbcontext-access-in-dataloaders-graphql-nested-querie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!