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

时间:2018-03-23 14:05:40

标签: 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) );

我根据缺少的参数收到很多错误,是否有正确的方法将实例移出控制器?

1 个答案:

答案 0 :(得分:1)

  

我无法访问DI。

此解释不正确,您可以在另一个程序集read more中注入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
    }
}

在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 ...
 }