title: How to Dispose() after every HTTP request using Scoped Service in OnModelCreating()?
body: <p>I have a multi-tenant app and for every <code>HTTP Request</code> it should validate the <code>Headers</code> for the property <code>AccountId</code>.</p>
  <p><strong>Global query filters</strong> are a good way to isolate tenants mentioned in <a href="https://docs.microsoft.com/en-us/ef/core/querying/filters" rel="nofollow noreferrer">.NET Core Docs</a> but it doesn't list how you can dispose state after each request.</p>
  <p>Here is an example:</p>
  <p><strong>ApplicationDbContext.cs</strong>
  Has a global query filter for <code>Account</code> entity using <code>AccountId</code> injected by the <code>FooHeaderService</code></p>
  <pre class="lang-cs prettyprint-override"><code>private readonly IFooHeader _fooHeaders;
  
  public ApplicationDbContext(IFooHeader fooHeaders) : base(options)
  {
      this._fooHeaders = fooHeaders;
  }
  
  protected override void OnModelCreating() {
      FooHeaders foo = this._fooHeaders.GetFooHeaders().AccountId;
  
      // or using Microsoft.EntityFrameworkCore.Infrastructure
      FooHeaders foo = this.Database.GetService&lt;IFooHeaders&gt;();
      Guid fooId = foo.AccountId;     // MUST DISPOSE BETWEEN REQUESTS!
  
      // Global Query Filter
      modelBuilder.Entity&lt;Account&gt;()
          .HasQueryFilter(filter =&gt; filter.AccountId = fooId)
  }
  </code></pre>
  <p><strong>FooHeaderService</strong>
  Gets the <code>Headers</code> for <code>AccountId</code></p>
  <pre class="lang-cs prettyprint-override"><code>public class FooHeaderService : IFooHeaders
  {
      private readonly FooHeaders _headers;
  
      public FooHeaderService(IHttpContextAccessor contextAccessor)
      {
          _headers.AccountId = contextAccessor.HttpContext?.Request
               .Headers[&quot;accountId&quot;].ToString();
      }
  
      public FooHeaders GetFooHeaders() =&gt; _headers;
  }
  </code></pre>
  <p><strong>Startup.cs</strong>
  Register <code>FooHeaderService</code> as <code>ScopedService</code></p>
  <pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
  {
      services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
      services.AddScoped&lt;IFooHeader, FooHeaderService&gt;();
  
      services.AddDbContext&lt;ApplicationDbContext&gt;();
  }
  </code></pre>
  <p><strong>Issue</strong></p>
  <p>Without properly disposing, the variable <code>fooId = AccountId</code> inside <code>OnModelCreating()</code> persists between <code>HTTP Requests</code> (very dangerous stuff!).</p>
  <p><strong>How do you dependency inject <code>FooHeaderService</code> into <code>OnModelCreating()</code> and dispose state for each <code>HTTP Request</code> cycle?</strong></p>