title: Create EF Core Context once per request in ASP.Net Core
body: <p>After reading a lot on the subject it looks like a good approach is to create a context once per request.</p>
  
  <p>To achive this, in in Startup.cs I have declared two statics objects</p>
  
  <pre><code>public class Startup
  {
      public static DbContextOptionsBuilder&lt;MCContext&gt; optionsBuilder = new DbContextOptionsBuilder&lt;MCContext&gt;();
      public static MCContext db = null;
  </code></pre>
  
  <p>then init optionsBuilder when the app starts (so only once):</p>
  
  <pre><code>public Startup(IConfiguration configuration)
  {
      optionsBuilder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"]);
  }
  </code></pre>
  
  <p>while db at each request:</p>
  
  <pre><code>app.Use(async (context, next) =&gt;
  {
      db = db ?? new MCContext(optionsBuilder.Options);
      await next.Invoke(); 
  });
  </code></pre>
  
  <p>Then when I need the context in a controller or in a razor page cs I can get it using Startup.db:</p>
  
  <pre><code>User cur = await Startup.db.User.Where(x =&gt; x.Id == uid).FirstOrDefaultAsync();
  </code></pre>
  
  <p>I do not Dispose the Context as per <a href="https://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/" rel="noreferrer">here</a></p>
  
  <p>As I'm not familiar with DI I wonder if this approach is correct or if I am missing anything.</p>