title: What is the recommended way to run asp.net identity functions in transaction?
body: <p>Using asp.net identity <a href="https://stackoverflow.com/questions/18793746/how-can-i-get-early-access-to-upcoming-asp-net-identity-changes">RTW version</a>.</p>
  
  <p>I need to perform several actions in a transaction, including both <code>UserMananger</code> function calls and other operations on my <code>DbContext</code> (example: create new user, add it to group and perform some business-logic operations).</p>
  
  <p>How should I do this?</p>
  
  <p>My thoughts follow.</p>
  
  <p><strong>TransactionScope</strong></p>
  
  <pre><code>using (var scope = new TransactionScope(TransactionScopeOption.Required))
  {
      // Do what I need
      if (everythingIsOk) scope.Complete();
  }
  </code></pre>
  
  <p>The problem is: <code>UserManager</code> functions are all async, and <code>TransactionScope</code> was not designed to work with async/await. <a href="https://stackoverflow.com/a/17527843/1234444">It seems to be solved in .Net Framework 4.5.1</a>. But I use Azure Web Sites to host my project builds, so I cannot target 4.5.1 yet.</p>
  
  <p><strong>Database transaction</strong></p>
  
  <pre><code>public class SomeController : Controller
  {
      private MyDbContext DbContext { get; set; }
      private UserManager&lt;User&gt; UserManager { get; set; }
  
      public AccountController()
      {
          DbContext = new MyDbContext()
          var userStore = new UserStore&lt;IdentityUser&gt;(DbContext);
          UserManager = new UserManager&lt;IdentityUser&gt;(userStore);
      }
  
      public async ActionResult SomeAction()
      {
          // UserManager uses the same db context, so they can share db transaction
          using (var tran = DbContext.Database.BeginTransaction())
          {
              try
              {
                  // Do what I need
                  if (everythingIsOk)
                      tran.Commit();
                  else
                  {
                      tran.Rollback();
                  }
              }
              catch (Exception)
              {
                  tran.Rollback();
              }
          }
      }
  }
  </code></pre>
  
  <p>That seems to work, but how can I unit-test it?</p>
  
  <p><code>UserManager&lt;&gt;</code> constructor accepts <code>IUserStore&lt;&gt;</code>, so I can easily stub it.</p>
  
  <p><code>UserStore&lt;&gt;</code> constructor accepts <code>DbContext</code>, no idea how I can stub this.</p>