【发布时间】:2013-10-16 01:36:31
【问题描述】:
使用 asp.net 身份RTW version。
我需要在事务中执行几个操作,包括UserMananger 函数调用和我的DbContext 上的其他操作(例如:创建新用户,将其添加到组并执行一些业务逻辑操作)。
我应该怎么做?
我的想法随之而来。
事务范围
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
// Do what I need
if (everythingIsOk) scope.Complete();
}
问题是:UserManager 函数都是异步的,而TransactionScope 并非设计用于异步/等待。 It seems to be solved in .Net Framework 4.5.1。但是我使用 Azure 网站来托管我的项目构建,所以我还不能以 4.5.1 为目标。
数据库事务
public class SomeController : Controller
{
private MyDbContext DbContext { get; set; }
private UserManager<User> UserManager { get; set; }
public AccountController()
{
DbContext = new MyDbContext()
var userStore = new UserStore<IdentityUser>(DbContext);
UserManager = new UserManager<IdentityUser>(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();
}
}
}
}
这似乎可行,但我该如何对其进行单元测试?
UserManager<> 构造函数接受IUserStore<>,所以我可以轻松地存根它。
UserStore<> 构造函数接受DbContext,不知道如何存根。
【问题讨论】:
标签: asp.net-mvc-5 asp.net-identity