【问题标题】:UserManager's AutoSaveChanges in .NET Core 2.1.NET Core 2.1 中的 UserManager 的 AutoSaveChanges
【发布时间】:2018-11-23 13:44:46
【问题描述】:

我想禁用 UserManager 的自动 SaveChanges 方法调用。我发现可以通过设置 UserStore 的 AutoSaveChanges 属性来实现。但是 .NET Core 2.1 中此类事情的最佳实践是什么?是否可以通过配置 IdentityBuilder 在 Startup.cs 中进行?

【问题讨论】:

    标签: c# .net asp.net-web-api asp.net-core


    【解决方案1】:

    您需要创建一个继承Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<IdentityUser>形式的类,并在构造函数中将AutoSaveChanges设置为false,然后在AddEntityFrameworkStores之前将该类注册到IServiceCollection

    public class CustomUserStore : UserStore<IdentityUser>
    {
        public CustomUserStore(ApplicationDbContext context)
            : base(context)
        {
            AutoSaveChanges = false;
        }
    }
    

    Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<IUserStore<IdentityUser>, CustomUserStore>();
    
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
    
        services.AddDefaultIdentity<IdentityUser>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>();
    }
    

    【讨论】:

    • 然后默认的UserManager会捡起来使用吗?
    • 是的,UserManager 依赖于由services.AddScoped&lt;IUserStore&lt;IdentityUser&gt;, CustomUserStore&gt;() 注册的IUserStore&lt;T&gt;
    • 很遗憾我目前无法测试,但听起来很有希望!我会接受的
    • 在 .NET 5 中仍然有效。有关实施的更多详细信息,请参考较新的问题。 stackoverflow.com/questions/69843463/…
    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 2018-12-25
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    相关资源
    最近更新 更多