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

Joe*_*ttz 3 c# asp.net-identity asp.net-core

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

在 Startup.ConfigureServices() 我有:

services.AddIdentity<IdentityUser, IdentityRole>();
Run Code Online (Sandbox Code Playgroud)

在我的课堂上,我有:

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

    public Auth(..., SignInManager<IdentityUser> signInManager)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到这个例外:

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

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

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

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

Dav*_*idG 5

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

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

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

services.AddDefaultIdentity<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)