【问题标题】:How can I access UserManager and RoleManager from a Console App?如何从控制台应用程序访问 UserManager 和 RoleManager?
【发布时间】:2015-12-12 16:04:36
【问题描述】:

如何在非托管的 控制台应用程序包中访问UserManager 和/或RoleManger

【问题讨论】:

    标签: asp.net-5 c# asp.net asp.net-core entity-framework-core


    【解决方案1】:

    Program.cs

    public class Program
    {
        public void Main(string[] args)
        {
            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
    
            // do whatever
        }
    
        private readonly IServiceProvider serviceProvider;
    
        public IConfigurationRoot Configuration { get; private set; }
    
        public Program(IApplicationEnvironment env, IServiceManifest serviceManifest)
        {
            Configuration =
                new ConfigurationBuilder(Directory.GetCurrentDirectory())
                .AddJsonFile("config.json") // add the file to your project
                .AddEnvironmentVariables()
                .Build();
    
            var services = new ServiceCollection();
            ConfigureServices(services);
            serviceProvider = services.BuildServiceProvider();
        }
    
        private void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
    
            // Register EntityFramework 7
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(connectionString));
    
            // Register UserManager & RoleManager
            services.AddIdentity<ApplicationUser, IdentityRole>()
               .AddEntityFrameworkStores<ApplicationDbContext>()
               .AddDefaultTokenProviders();
    
            // UserManager & RoleManager require logging and HttpContext dependencies
            services.AddLogging();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }
    }
    

    config.json

    {
      "Data": {
        "DefaultConnection": {
          "ConnectionString": "Server=(localdb)\\ProjectsV12;Database=my-database-name;Integrated Security=true;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
      }
    }
    

    【讨论】:

    • 这需要哪些软件包?
    猜你喜欢
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    相关资源
    最近更新 更多