title: Thread Safe Unit of Work with EntityFramework
body: <p>I have a Data Layer that uses one Unit of work that is is basically a wrapper of the EnityFramework data context.</p>
  
  <p>With all the async await stuff going around, I thought I'd start trying to use this data layer with some async calls.  (I'm new to asynchronous programming in general)</p>
  
  <p>I quickly ran into the problem of "there is already an open data reader associated with this command" errors.</p>
  
  <p>Is there a good way to make my Unit of work thread-safe?  Or should I just be creating another instance of it when i'm about to make some calls (in others words..be more careful).</p>
  
  <p>Are there any good resources to check out for doing this?  </p>
  
  <p>My few google searches didn't amount to much, so I thought I'd bring this question to SO.</p>
  
  <p>My Uow looks something like this.</p>
  
  <pre><code>public class MyUnitOfWork: IMyUnitOfWork, IDisposable
  {
      private MyDbContext DbContext { get; set; }
      protected IRepositoryProvider RepositoryProvider;
  
      public MyUnitOfWork(IRepositoryProvider repositoryProvider)
      {
          CreateDbContext();
  
  
          repositoryProvider.DbContext = DbContext;
          RepositoryProvider = repositoryProvider;
      }
  
      public MyUnitOfWork(IRepositoryProvider repositoryProvider, MyDbContext context)
      {
          DbContext = context;
  
          repositoryProvider.DbContext = DbContext;
          RepositoryProvider = repositoryProvider;
  
      }
      public void CreateDbContext()
      {
          DbContext = new MyDbContext();
  
          //Serialization false if we enable proxied entities
          DbContext.Configuration.ProxyCreationEnabled = false;
  
          //avoid serilaization trouble
          DbContext.Configuration.LazyLoadingEnabled = false;
      }
      public void Commit()
      {
          DbContext.SaveChanges();
      }
  
      public IRepository&lt;Person&gt; Persons {get { return repositoryProvider.GetRepo&lt;Person&gt;(); } }
  
      public IRepository&lt;SomeOtherEntityType&gt; SomeOtherType {get { return repositoryProvider.GetRepo&lt;SomeOtherEntityType&gt;(); } }
  
      // IDisposable 
      // ...
  }
  </code></pre>