gpt4 book ai didi

c# - 如何从控制台应用程序访问 UserManager 和 RoleManager?

转载 作者:行者123 更新时间:2023-11-30 14:52:04 30 4
gpt4 key购买 nike

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

最佳答案

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"
}
}
}

关于c# - 如何从控制台应用程序访问 UserManager 和 RoleManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32602327/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com