c# - 尝试激活 yyy 时无法解析类型 xxx 的服务

标签 c# asp.net-core

<分区>

我有一个启用了身份的 asp.net core 2.1 项目,但是在对种子用户进行某些更改后,我遇到了一些问题。

点击注册为新用户时出现的错误是

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UI.Services.IEmailSender' while attempting to activate 'namespace.Website.Main.Areas.Identity.Pages.Account.RegisterModel'.

在 Register.cshtml.cs 类中,我看到注入(inject)了 IEmailSender,但我没有对此进行任何更改,无法理解为什么会发生此错误?请帮忙

启动.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddHttpClient();

        services.AddHttpClient<IExceptionServiceClient, ExceptionServiceClient>();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }
}

角色配置

public static class RolesConfig
{
    public static async Task InitialiseAsync(ApplicationDbContext context, IServiceProvider serviceProvider)
    {
        var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        string[] roleNames = { "Admin", "Report", "Search" };
        foreach (var roleName in roleNames)
        {
            var roleExist = await roleManager.RoleExistsAsync(roleName);
            if (!roleExist)
                await roleManager.CreateAsync(new IdentityRole(roleName));
        }
    }
}

注册.cshtml.cs

public class RegisterModel : PageModel
{
    private readonly SignInManager<IdentityUser> _signInManager;
    private readonly UserManager<IdentityUser> _userManager;
    private readonly ILogger<RegisterModel> _logger;
    private readonly IEmailSender _emailSender;

    public RegisterModel(
        UserManager<IdentityUser> userManager,
        SignInManager<IdentityUser> signInManager,
        ILogger<RegisterModel> logger,
        IEmailSender emailSender)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _logger = logger;
        _emailSender = emailSender;
    }

    [BindProperty]
    public InputModel Input { get; set; }

    public string ReturnUrl { get; set; }

    public class InputModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

    public void OnGet(string returnUrl = null)
    {
        ReturnUrl = returnUrl;
    }

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        if (ModelState.IsValid)
        {
            var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
            var result = await _userManager.CreateAsync(user, Input.Password);
            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");

                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                var callbackUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { userId = user.Id, code = code },
                    protocol: Request.Scheme);

                await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                await _signInManager.SignInAsync(user, isPersistent: false);
                return LocalRedirect(returnUrl);
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }

        // If we got this far, something failed, redisplay form
        return Page();
    }
}

非常感谢任何帮助!谢谢

最佳答案

问题是您在 RegisterModel 中使用 IEmailSender 彻底的构造函数依赖注入(inject),但您没有将 IEmailSender 注册到 ASP.NET Core DI 容器.因此,要注册 IEmailSender,请将以下行添加到 Startup 类的 ConfigureServices 方法中:

services.AddScoped<IEmailSender,EmailSender>();

现在问题应该消失了。

关于c# - 尝试激活 yyy 时无法解析类型 xxx 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54871629/

相关文章:

c# - 机器人框架禁用用户输入框

c# - IBM DB2 问题--System.BadImageFormatException : Could not load file or assembly IBM. DB2.DLL 或其依赖项之一

c# - 如何使用数据库优先方法读取 asp.net core 中的表

iis - ASP.net 5 自托管在 Live Windows Server 上 - EACCES 权限被拒绝?

dependency-injection - ASP.NET 5 DI 连接字符串到 ADO.NET

c# - 对界面对象列表进行排序

c# - 如何最小化序列化数据的大小

c# - 外部注销后如何重定向到设置注销页面(openid Connect)Asp net core 3.1

asp.net-core - 如何配置 ASP.Net TestHost 以便与 OpenId Connect 一起使用?

c# - 为 Entity Framework 4.3 禁用数据库初始化