title: EF Core DbContext being disposed of before Async methods are complete
body: <p>I am having issues where my DbContext is being disposed of early. It is only ever apparent when calling any of the *Async methods, such as <code>ToListAsync()</code> - if i call any of the syncronous methods everything is fine.</p>
  
  <p>I can't figure out what I'm doing wrong.</p>
  
  <p>Any advise please?</p>
  
  <p>Here is as much of the code as i believe is needed.</p>
  
  <p>The DbContext and its interface</p>
  
  <pre><code>public interface IMyDbContext
  {
      DbSet&lt;MyModel&gt; MyModels { get; set; }
  }
  
  public class MyDbContext : DbContext, IMyDbContext
  {
      public DbSet&lt;MyModel&gt; MyModels { get; set; }
  
      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      {
          optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
  
      }
  
      public MyDbContext(DbContextOptions&lt;MyDbContext&gt; options) : base(options) { }
  
      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
          modelBuilder.ApplyConfiguration(new MyModelConfig());           
      }
  }
  </code></pre>
  
  <p>A Repository using this DbContext</p>
  
  <pre><code>public class MyModelRepository : IMyModelRepository
  {
      private readonly IMyDbContext _dbContext;
      private string _baseSql = "Some SQL here ";
  
      public MyModelRepository(IMyDbContext dbContext)
      {
          _dbContext = dbContext;
      }
  
      public async Task&lt;IList&lt;MyModel&gt;&gt; GetAllAsync(Paging paging, Permission permission)
      {
  
          if (permission == null)
              throw new ArgumentNullException("permission");
  
          string sql = ApplyFilter(_baseSql, permission);
  
          try
          {
              // THIS FAILS
              return await _dbContext.MyModels.FromSql(sql).Skip(paging.Skip).Take(paging.Take).ToListAsync();
  
              // THIS FAILS
              return await _dbContext.MyModels.FromSql(sql).ToListAsync();
  
              // THIS WORKS
              return await _dbContext.MyModels.FromSql(sql).ToList(); 
  
          }
          catch (Exception e)
          {
  
              throw new InvalidOperationException("Could not retrieve data", e);
          }
      }
  }
  </code></pre>
  
  <p>I'm calling the repo via a service that looks like this:</p>
  
  <pre><code>public class GetAllMyModelQuery : IGetAllMyModelQuery
  {
      private readonly IMyModelRepository _myModelRepository;
      private readonly IPermissionService _permissionService;
      private readonly ILogger _logger;
  
      public GetAllAbsenceQuery(IMyModelRepository myModelRepository, IPermissionService permissionService, ILogger&lt;GetAllMyModelQuery&gt; logger)
      {
          _myModelRepository = myModelRepository;
          _permissionService = permissionService;
          _logger = logger;
      }
  
      public async Task&lt;IList&lt;Emp_AbsenceEtrac&gt;&gt; Execute(Paging paging)
      {
          if (_permissionService.Permission == null)
          {
              _logger.LogInformation("No permission to the requested resource");
              return null;
          }
  
          // if external?
          // call external repo
  
          //TODO//
  
          // else
          return await _myModelRepository.GetAllAsync(paging, _permissionService.Permission);
      }
  }
  </code></pre>
  
  <p>This in turn is called by the controller</p>
  
  <pre><code>public class MyModelController : Controller
  {
      private readonly IQueryStore _queryStore;
  
      public MyModelController(IQueryStore queryStore)
      {
          _queryStore = queryStore;
      }
  
      [HttpGet]
      [ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
      [ProducesResponseType(typeof(BadRequestObjectResult), (int)HttpStatusCode.BadRequest)]
      public async Task&lt;IActionResult&gt; Index([FromQuery] int offset = 0, [FromQuery] int limit = 25)
      {
          Paging paging = new Paging(offset, limit);
          return Ok(_queryStore.GetAllMyModelQuery.Execute(paging));
      }
  }
  </code></pre>
  
  <p>Finally, it's all wired together in the startup:</p>
  
  <pre><code>services.AddScoped&lt;IMyDbContext, MyDbContext&gt;();
  services.AddScoped&lt;IMyModelRepository, MyModelRepository&gt;();    
  // Everything else above is also added as scope..
  
   services.AddDbContext&lt;MyDbContext&gt;(opts =&gt;
  {
      opts.UseSqlServer(Configuration.GetConnectionString("MyDb"),
          sqlServerOptions =&gt;
          {
              sqlServerOptions.CommandTimeout(600);
              // required to allow skip/take on sql server 2008
              sqlServerOptions.UseRowNumberForPaging(true);
          });
  }); 
  </code></pre>
  
  <p>Is there anything jumping out that would cause my Async calls to result in a closed Db connection?</p>
  
  <p>Error is:</p>
  
  <p><a href="https://i.stack.imgur.com/AP23i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AP23i.png" alt="enter image description here"></a></p>