【发布时间】:2020-10-13 03:24:17
【问题描述】:
我创建了一个类
public class DefaultLogin
{
[Inject]
public UserManager<ApplicationUser> userManager { get; set; }
public DefaultLogin(UserManager<ApplicationUser> userManager)
{
this.userManager = userManager;
}
}
我尝试使用[Inject] 属性来解析UserManager<ApplicationUser>。但它没有奏效。我不确定为什么有时可以像在派生自ComponentBase 的类中那样使用它。也许有人知道为什么?
所以注入属性不起作用。我删除了[Inject] 并创建了一个构造函数,而不是上面代码中的[Inject]。我现在的问题是如何实例化 DefaultLogin 类?
我做不到:
new DefaultLogin();
我不想这样做:
serviceCollection.AddScoped<DefaultLogin>();
我想做这样的事情(扩展类):
public static void UseDefaultLogin(this IApplicationBuilder app)
{
var configuration = (IConfiguration) app.ApplicationServices.GetService(typeof(IConfiguration));
var userManager = (UserManager<ApplicationUser>) app.ApplicationServices.GetService(typeof(UserManager<ApplicationUser>));
string defaultUserUserName = configuration["DefaultUser:UserName"];
string defaultUserEmail = configuration["DefaultUser:Email"];
string defaultUserPassword = configuration["DefaultUser:Password"];
if (userManager.FindByEmailAsync(defaultUserEmail).Result == null)
{
ApplicationUser user = new ApplicationUser
{
UserName = defaultUserUserName,
Email = defaultUserEmail ?? defaultUserUserName
};
IdentityResult result = userManager.CreateAsync(user, defaultUserPassword).Result;
if (result.Succeeded)
{
userManager.AddToRoleAsync(user, "Admin").Wait();
}
}
}
IConfiguration 可以解决。
但是UserManager<ApplicationUser>不是,
无法从根提供商解析范围服务“Microsoft.AspNetCore.Identity.UserManager`1[InfoApp.Repository.ApplicationUser]”
我在 Startup 类的 Configure 方法末尾调用 app.UseDefaultLogin();。
【问题讨论】:
-
Something 在 IoC 链/图的“顶部”必须执行一些动作作为“服务定位器样式”。例如,这是由控制器(内部)完成的。因此,如果 DefaultLogin 被注入到控制器中,那么它将在那里被解析,进而解析它自己的依赖项。
标签: c# asp.net asp.net-core dependency-injection