![](/img/trans.png)
[英]How to Unit Test Asp.Net MVC Identity UserManager.ChangePasswordAsync
[英]Asp.Net Identity Usermanager and Unit Of Work - how to mate them?
我正在使用工作单元模式,并在一个名为MyProject.Domain.DAL.UnitOfWork的单独子项目中为其定义了一个类。
不幸的是,整个ASP.Net Identity基础结构都在我的主项目(如本教程中)MyProject中。
更成问题的是:据我所知,ASP.NET身份使用它自己的DBContext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationDbContext"/> class, using the EFDB context.
/// </summary>
public ApplicationDbContext()
: base("EFDBContext", throwIfV1Schema: false)
{
}
/// <summary>
/// Creates this instance.
/// </summary>
/// <returns>A database context</returns>
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
我有一个名为Project的类,该类应具有与其相关联的用户-但是如何在不使用冲突的数据库上下文的情况下做到这一点?
例:
public class Project
{
public ApplicationUser User {get; set;}
}
调用代码示例:
public class IndexController : Controller
{
// uow and userManager are instantiated through Ninject
// example code, normally this would be properties of the controller
public ActionResult Create(IUnitOfWork uow, ApplicationUserManager userManager, int someID )
{
Project newProject = new Project();
ApplicationUser user = await UserManager.FindByIdAsync(someID);
// this should give a conflict, since two different DataContexts are involved
newProject.User = user;
uow.Projects.Insert(newProject);
uow.Save()
return this.View();
}
}
}
模板有点混乱。 您不应创建单独的DbContext
,而应使用其余数据模型扩展现有的ApplicationDbContext
。 您可以将其移动到项目中的其他位置,只要更改IdentityConfig.cs
的类型即可。
尽管使用工作单元时要解决一个更棘手的问题,那就是ASP.NET Identity方法在内部调用SaveChanges()
而当使用工作单元时,通常只希望在完成所有工作后才希望。 一种解决方法是使用TransactionScope()
但在ASP.NET Identity使用的按请求的DbContext之前创建它可能很麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.