【问题标题】:ASP.NET Core dependency injection c# how to instantiate classes?ASP.NET Core依赖注入c#如何实例化类?
【发布时间】: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&lt;ApplicationUser&gt;。但它没有奏效。我不确定为什么有时可以像在派生自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&lt;ApplicationUser&gt;不是,

无法从根提供商解析范围服务“Microsoft.AspNetCore.Identity.UserManager`1[InfoApp.Repository.ApplicationUser]”

我在 Startup 类的 Configure 方法末尾调用 app.UseDefaultLogin();

【问题讨论】:

  • Something 在 IoC 链/图的“顶部”必须执行一些动作作为“服务定位器样式”。例如,这是由控制器(内部)完成的。因此,如果 DefaultLogin 被注入到控制器中,那么它将在那里被解析,进而解析它自己的依赖项。

标签: c# asp.net asp.net-core dependency-injection


【解决方案1】:

您必须使用第二种方法,即构造函数注入。

要使用DefaultLogin 对象,您可以在需要它的类中执行相同的操作。

假设您有一个LoginController。这应该有效:

public class LoginController : ControllerBase
{

   private readonly DefaultLogin _defaultLogin;
   
   public LoginController(DefaultLogin defaultLogin)
   {
      _defaultLogin = defaultLogin;
   }
}

注意:一般的经验法则是将注入的引用保存为字段,而不是属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 2018-03-23
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2017-04-12
    • 2018-03-10
    • 1970-01-01
    相关资源
    最近更新 更多