title: How to execute method before scoped service is disposed in asp.net core?
body: <p>I have a custom middleware whose purpose is to subscribe to EF Core dbcontext events and track the changes that happen to the entities. 
  The middleware instantiates my InteractionService as a scoped instance at the beginning of each request. This is how my middleware looks like:</p>
  
  <pre><code>public static IApplicationBuilder UseDbContextActivityTracker&lt;TContext&gt;(this IApplicationBuilder app)
      where TContext : DbContext
  {
      app.Use(async (context, next) =&gt;
      {
          var service = context.RequestServices.GetRequiredService&lt;InteractionService&lt;TContext&gt;&gt;();
          await next.Invoke();
          service.PersistLogs();
      });
  
      return app;
  }
  </code></pre>
  
  <p>and this is how I use the middleware in my Confiure method of the Startup class:</p>
  
  <pre><code>options.UseDbContextActivityTracker&lt;ApplicationDbContext&gt;();
  </code></pre>
  
  <p>In the constructor of my InteractionService I get a reference to the dbcontext through the DI and I subscribe to the events:</p>
  
  <pre><code>public InteractionService(TContext context)
  {
      this.context = context;
      this.context.ChangeTracker.StateChanged += ChangeTracker_StateChanged;
  }
  </code></pre>
  
  <p>While listening to the events that happen to the dbContext during the duration of a request I am storing relevant information into my own entities and it works great. However, at the end of the request, I want to save changes to the database. I tried making my InteractionService class IDisposable and in the Dispose method, I am invoking another DbContext in which I save my entities. As expected I got the error "Connection already closed". 
  <strong>What is the right place to save my entities to the db after the request has been finished?</strong></p>