title: EF Core DbContext ObjectDisposedException
body: <p>having EF core 2.2 and .net core 2.2 I am struggling with ObjectDisposedException issues like:
  <a href="https://stackoverflow.com/questions/13617698/the-operation-cannot-be-completed-because-the-dbcontext-has-been-disposed-error">here</a> and <a href="https://stackoverflow.com/questions/38704025/cannot-access-a-disposed-object-in-asp-net-core-when-injecting-dbcontext">here</a> </p>
  
  <p>few facts:</p>
  
  <ul>
  <li>all my services are registered as Transient, same with DbContext using <code>AddDbContext()</code></li>
  <li>using DI to inject <code>DbContext</code> instance</li>
  <li>all functions mentioned in stack trace are <code>async</code>/<code>await</code></li>
  </ul>
  
  <p>I feel that I am missing something obvious here but I have spent already 2-3 days on this without any luck</p>
  
  <p>stack trace:</p>
  
  <pre><code>Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware [8] - An unhandled exception has occurred while executing the request. System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
  Object name: 'BaseContext'.
     at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
     at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
     at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies.get_QueryProvider()
     at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ParameterExtractingExpressionVisitor..ctor(IEvaluatableExpressionFilter evaluatableExpressionFilter, IParameterValues parameterValues, IDiagnosticsLogger`1 logger, DbContext context, Boolean parameterize, Boolean generateContextAccessors)
     at Microsoft.EntityFrameworkCore.Query.Internal.QueryModelGenerator.ExtractParameters(IDiagnosticsLogger`1 logger, Expression query, IParameterValues parameterValues, Boolean parameterize, Boolean generateContextAccessors)
     at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query)
     at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.System.Collections.Generic.IAsyncEnumerable&lt;TResult&gt;.GetEnumerator()
     at System.Linq.AsyncEnumerable.Aggregate_[TSource,TAccumulate,TResult](IAsyncEnumerable`1 source, TAccumulate seed, Func`3 accumulator, Func`2 resultSelector, CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Aggregate.cs:line 118
     at Sample.Infrastructure.Tasks.TagEventTypeTasks.GetAllAsync() in ~root\Sample.API\Sample.Infrastructure\Tasks\TagEventTypeTasks.cs:line 24
     at Sample.API.Helpers.GraphHelpers.GetAllTagEventTypesWithCacheAsync() in ~root\Sample.API\Sample.API\Helpers\GraphHelpers.cs:line 45
     at Sample.API.Controllers.GraphController.GetTagEventTypeTimesAsync() in ~root\Sample.API\Sample.API\Controllers\GraphController.cs:line 59
     at lambda_method(Closure , Object )
     at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
     at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
     at System.Threading.Tasks.ValueTask`1.get_Result()
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
     at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
     at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
     at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
     at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context)
  </code></pre>
  
  <p>for full transparency, here are the methods mentioned in stack trace:</p>
  
  <p>GraphController.cs:</p>
  
  <pre><code>[HttpGet("tagEventTypeTimes")]
  public async Task&lt;ActionResult&lt;List&lt;TagEventTypeResultDto&gt;&gt;&gt; GetTagEventTypeTimesAsync()
  {
      return await _graphHelpers.GetAllTagEventTypesWithCacheAsync();
  }
  </code></pre>
  
  <p>GraphHelpers.cs:</p>
  
  <pre><code>public async Task&lt;List&lt;TagEventType&gt;&gt; GetAllTagEventTypesWithCacheAsync()
  {
      string tagEventTypesKey = "tagEventTypes";
      List&lt;TagEventType&gt; tagEventTypes;
      if (!_cache.TryGetValue&lt;List&lt;TagEventType&gt;&gt;(tagEventTypesKey, out tagEventTypes))
      {
          tagEventTypes = await _tagEventTypeTasks.GetAllAsync();
          _cache.Set&lt;List&lt;TagEventType&gt;&gt;(tagEventTypesKey, tagEventTypes, _memCacheOptions);
      }
  
      return tagEventTypes;
  }
  </code></pre>
  
  <p>TagEventTypeTasks.cs:</p>
  
  <pre><code>public class TagEventTypeTasks : ITagEventTypeTasks
  {
      private readonly BaseContext _context;
  
      public TagEventTypeTasks(BaseContext context)
      {
          _context = context;
      }
  
      public async Task&lt;List&lt;TagEventType&gt;&gt; GetAllAsync()
      {
          return await _context.TagEventType.OrderByDescending(x =&gt; x.Id).AsNoTracking().ToListAsync();
      }
  }
  </code></pre>
  
  <p>BaseContext.cs:</p>
  
  <pre><code>public class BaseContext : DbContext
  {
      private readonly ILoggerFactory _logger;
  
      public BaseContext(DbContextOptions&lt;BaseContext&gt; options, ILoggerFactory logger) : base(options)
      {
          _logger = logger;
      }
  
      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      {
          optionsBuilder.UseLoggerFactory(_logger);
      }
  
      public DbSet&lt;Patient&gt; Patient { get; set; }
      public DbSet&lt;Room&gt; Room { get; set; }
      public DbSet&lt;Tag&gt; Tag { get; set; }
      public DbSet&lt;TagEvent&gt; TagEvent { get; set; }
      public DbSet&lt;TagEventType&gt; TagEventType { get; set; }
      public DbSet&lt;TagLocation&gt; TagLocation { get; set; }
      public DbSet&lt;TagRegistration&gt; TagRegistration { get; set; }
      public DbSet&lt;User&gt; User { get; set; }
  
      protected override void OnModelCreating(ModelBuilder builder)
      {
          builder.ApplyConfiguration(new PatientConfiguration());
          builder.ApplyConfiguration(new TagConfiguration());
          builder.ApplyConfiguration(new TagRegistrationConfiguration());
          builder.ApplyConfiguration(new TagEventConfiguration());
          builder.ApplyConfiguration(new TagEventTypeConfiguration());
          builder.ApplyConfiguration(new TagLocationConfiguration());
          builder.ApplyConfiguration(new RoomConfiguration());
      }
  }
  </code></pre>
  
  <p><strong>UPDATE:</strong>
  added startup related code</p>
  
  <pre><code>services.AddDbToServices(Configuration.GetConnectionString("DefaultConnection"));
  
  public static void AddDbToServices(this IServiceCollection services, string connectionString)
  {
      services.AddDbContext&lt;BaseContext&gt;(options =&gt; options.UseFirebird(connectionString), ServiceLifetime.Transient);
  }
  </code></pre>
  
  <p><strong>UPDATE2</strong></p>
  
  <p>added whole <code>TagEventTypeTasks</code> class</p>
  
  <p><strong>UPDATE3</strong></p>
  
  <p>added services register
  I am using this <a href="https://github.com/JonPSmith/NetCore.AutoRegisterDi" rel="nofollow noreferrer">lib</a> however I tried to register all services manually using <code>AddTransient()</code> -> also didn't help</p>
  
  <pre><code>var assembliesToScan = new[]
  {
      Assembly.GetExecutingAssembly(),
      Assembly.GetAssembly(typeof(Patient)),
      Assembly.GetAssembly(typeof(PatientTasks))
  };
  
  services
      .RegisterAssemblyPublicNonGenericClasses(assembliesToScan)
      .AsPublicImplementedInterfaces(ServiceLifetime.Transient);
  </code></pre>