【发布时间】:2019-08-26 21:45:26
【问题描述】:
我的教科书展示了一个构建身份服务的示例,下面是代码:
//startup.cs
public void Configure(IApplicationBuilder app) {
app.UseStatusCodePages();
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
//try to seed an admin account for the first time the app runs
AppIdentityDbContext.CreateAdminAccount(app.ApplicationServices, Configuration).Wait();
}
//AppIdentityDbContext.cs
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options) : base(options) { }
public static async Task CreateAdminAccount(IServiceProvider serviceProvider, IConfiguration configuration)
{
UserManager<AppUser> userManager = serviceProvider.GetRequiredService<UserManager<AppUser>>();
RoleManager<IdentityRole> roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
string username = configuration["Data:AdminUser:Name"];
string email = configuration["Data:AdminUser:Email"];
string password = configuration["Data:AdminUser:Password"];
string role = configuration["Data:AdminUser:Role"];
if (await userManager.FindByNameAsync(username) == null)
{
if (await roleManager.FindByNameAsync(role) == null)
{
await roleManager.CreateAsync(new IdentityRole(role));
}
AppUser user = new AppUser
{
UserName = username,
Email = email
};
IdentityResult result = await userManager.CreateAsync(user, password);
if (result.Succeeded)
{
await userManager.AddToRoleAsync(user, role);
}
}
}
}
然后教科书上写着:
因为我正在通过 IApplicationBuilder.ApplicationServices 提供程序访问范围服务, 我还必须在 Program 类中禁用依赖注入作用域验证功能,如下所示:
//Program.cs
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseDefaultServiceProvider(options => options.ValidateScopes = false)
.Build();
我对 DI 有基本的了解,但我对这个例子真的很困惑,以下是我的问题:
Q1- 通过 IApplicationBuilder.ApplicationServices 提供程序访问范围服务 这是什么意思?它试图访问哪些服务?为什么它的作用域不是瞬态的或单例的?
Q2- 为什么我们必须禁用依赖注入作用域验证,作用域验证试图实现什么?
【问题讨论】:
标签: c# dependency-injection asp.net-core-mvc