什么是在事务中运行asp.net身份的功能推荐的方式? [英] What is the recommended way to run asp.net identity functions in transaction?
问题描述
使用asp.net身份<一个href=\"http://stackoverflow.com/questions/18793746/how-can-i-get-early-access-to-upcoming-asp-net-identity-changes\">RTW版本。
Using asp.net identity RTW version.
我需要执行一个事务的几个动作,包括 UserMananger
在函数调用等操作我的的DbContext
(例如:创建新的用户,将其添加到组,并执行一些业务逻辑运算)
I need to perform several actions in a transaction, including both UserMananger
function calls and other operations on my DbContext
(example: create new user, add it to group and perform some business-logic operations).
我应该怎么做呢?
我的思绪随之而来。
的TransactionScope
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
// Do what I need
if (everythingIsOk) scope.Complete();
}
问题是:的UserManager
函数都是异步和的TransactionScope
不是设计与异步/的await工作。 似乎在.Net框架4.5.1 来解决。但是我用Azure网站主办我的项目生成,所以我无法针对4.5.1呢。
The problem is: UserManager
functions are all async, and TransactionScope
was not designed to work with async/await. It seems to be solved in .Net Framework 4.5.1. But I use Azure Web Sites to host my project builds, so I cannot target 4.5.1 yet.
数据库事务
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();
}
}
}
}
这似乎工作,但我怎么能单元测试?
That seems to work, but how can I unit-test it?
的UserManager&LT;&GT;
构造函数接受 IUserStore&LT;&GT;
,这样我就可以很容易地存根它
UserManager<>
constructor accepts IUserStore<>
, so I can easily stub it.
UserStore&LT;&GT;
构造函数接受的DbContext
,不知道我怎么能存根此
UserStore<>
constructor accepts DbContext
, no idea how I can stub this.
推荐答案
您可以实现可存根出你的单元测试自己的测试用户存储。
You can implement your own test user store that can be stubbed out for your unit test.
如果您要使用的实际EF UserStore在测试中,这也将工作,但它会使用默认DefaultConnection字符串创建数据库。你可以指定一个DatabaseInitializer总是降/重新创建你的测试你的表,如果你想确保干净分贝每一个测试。
If you want to use the actual EF UserStore in your tests, that also will work, but it will be creating a database using the DefaultConnection string by default. You could specify a DatabaseInitializer to always drop/recreate your tables in your tests if you wanted to ensure a clean db for every test.
这篇关于什么是在事务中运行asp.net身份的功能推荐的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!