繁体   English   中英

ASP.NET Core 2 导致 SignInManager 依赖项注入失败

[英]SignInManager dependency injection fails with ASP.NET Core 2

我试图在我的一个不是控制器的类中访问 Microsoft.AspNetCore.Identity.SignInManager。

在 Startup.ConfigureServices() 我有:

services.AddIdentity<IdentityUser, IdentityRole>();

在我的课堂上,我有:

public class Auth : IAuth
{
    ...
    private readonly SignInManager<IdentityUser> _signInManager;

    public Auth(..., SignInManager<IdentityUser> signInManager)
    {
    }
}

我得到这个例外:

处理请求时发生未处理的异常。 InvalidOperationException: 1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.AspNetUserManager 1[Microsoft.AspNetCore.Identity.IdentityUser]”时无法解析类型“Microsoft.AspNetCore.Identity.IUserStore 1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.AspNetUserManager的服务.

请注意,我什至没有在构造函数中引用传递的SignInManager对象(我是,但已将其删除以简化)。 如果我从构造函数中删除SignInManager参数一切正常。

我在网上看到的所有相关示例最终都是这样的情况,即在调用AddIdentity() SignInManager的指定用户数据类型与构造函数参数中的用户数据类型不匹配,但情况并非如此我的代码。

阅读相关文章和示例代码使这看起来应该是一项简单的任务。 我的构造函数的其他依赖注入参数工作得很好,只是如果我尝试注入RoleManager同样的问题(除了稍微不同的异常消息)。

添加身份后,您还没有配置任何数据存储。 文档中你应该做这样的事情:

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

但是,如果您使用的是 ASP.Net Core 2.1,请使用较新的版本:

services.AddDefaultIdentity<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

如果您使用的是 asp.net core 3.18 版本,请使用以下用户

services.AddDefaultIdentity<IdentityUser>()
         .AddEntityFrameworkStores<ApplicationDbContext>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM