title: Two (almost) concurrent DbContexts causing problems: How to share between Controller and AuthorizeAttribute
body: <p>Every once in a while, I'm encountering the following exception in my ASP.NET/MVC5/WebAPI2/EF6/MSSQL application:</p>
  
  <blockquote>
    <p>System.InvalidOperationException: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.</p>
  </blockquote>
  
  <p>I've traced this to my authorization code, which is a derivative of <code>AuthorizeAttribute</code> and instantiating its own <code>DbContext</code> to verify that my Web API consumer's API key is valid (the error occurs when trying to access the database).</p>
  
  <p>The <code>AuthorizeAttribute</code> in turn decorates controllers which are derivatives of my <code>BaseController</code>, which <strong>also</strong> instantiates a <code>DbContext</code> for controller work.</p>
  
  <p>After trying to troubleshoot this for days and reading <a href="https://stackoverflow.com/questions/12118562/ef-4-1-the-context-cannot-be-used-while-the-model-is-being-created-exception-d?lq=1">this</a> and <a href="https://stackoverflow.com/questions/6099781/how-can-i-prevent-ef-the-context-cannot-be-used-while-the-model-is-being-create?rq=1">this</a> I suspect that creating the two <code>DbContext</code> instances per request is the problem. However, I'm not quite sure how I can use only a single instance for this work. My controller code currently nicely instantiates the <code>DbContext</code> upon its own creation and disposes of it transparently when the controller itself disposes. The <code>AuthorizeAttribute</code> is completely independent from all this and creates the context on demand for its own purposes.</p>
  
  <p>Any patterns/ideas how to preserve/reuse the same <code>DbContext</code> for both units of work?</p>