如何在 ASP.NET MVC Core 2 中创建 UserManager 实例

Ehs*_*adi 5 c# asp.net-mvc asp.net-core asp.net-core-2.0

我正在尝试在 Mvc Core 2 中创建 UserManager 的实例,就像在 ASP.NET MVC 6 上使用以下代码所做的那样:

var UserManager = new UserManager<DbUser>(new UserStore<DbUser>(this) );
Run Code Online (Sandbox Code Playgroud)

由于缺少参数,我收到许多错误,是否有正确的方法在控制器之外获取实例?

Soh*_*deh 4

我无法访问 DI。

这个解释是不正确的,您可以注入UserManager另一个程序集阅读更多

只需创建一个用于播种数据的服务,例如:

public interface IInitializationService
{
    void Seed();
}

public class InitializationService : IInitializationService
{
    private readonly UserManager<ApplicationUser> _userManager;

    public InitializationService(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public void Seed()
    {
        // more code
    }
}
Run Code Online (Sandbox Code Playgroud)

在Startup.cs中注册服务

 public void ConfigureServices(IServiceCollection services)
 {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddTransient<IInitializationService, InitializationService>();

        services.AddMvc();
 }

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
        // more code ...

        var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
        using (var scope = scopeFactory.CreateScope())
        {
            var identityDbInitialize = scope.ServiceProvider.GetService<IInitializationService>();
            identityDbInitialize.Seed();
        }

      // more code ...
 }
Run Code Online (Sandbox Code Playgroud)