阻止 ASP.NET Identity 的 UserManager 自动保存

Prevent ASP.NET Identity's UserManager from automatically saving

我正在尝试与 ASP.NET Identity 及其 UserManager 集成。我有自己的自定义用户对象,我已将其添加到开箱即用的 ApplicationUser。 UserManager 有一个创建新用户的 Create() 方法(实际上它在 UserManagerExtensions class 中)。问题是它会自动将更改保存到已确认的数据库 here。我想在保存新用户之前在同一个 "transaction" 中执行一些其他操作,所以我不能让 UserManager 自动保存更改。

有趣的是,我在与 UserManager 相关联的 DbContext 中重写了 SaveChange() 方法,但它在 Create() 中自动保存的方法中从未中断。

有什么方法可以配置 UserManager 不自动保存更改。

此功能已默认实现 UserStore。因此你只需要配置它。在 ApplicationUserManager.Create() 静态方法中,或在实例化 UserStore 的任何地方,将 AutoSaveChanges 设置为 false

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
    var manager = new ApplicationUserManager(
        new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()) 
             { AutoSaveChanges = false });

    // rest of codes
}