如何访问的UserManager和RoleManager从一个控制台应用程序? [英] How can I access UserManager and RoleManager from a Console App?
本文介绍了如何访问的UserManager和RoleManager从一个控制台应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何访问的UserManager
和/或 RoleManger
在非托管,的 asp.net-5 控制台应用程序包?
How can I access UserManager
and/or RoleManger
in a non-hosted, asp.net-5 Console Application package?
推荐答案
的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"
}
}
}
这篇关于如何访问的UserManager和RoleManager从一个控制台应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文