gpt4 book ai didi

c# - ASP.NET Core 2 的 SignInManager 依赖注入(inject)失败

转载 作者:行者123 更新时间:2023-12-04 01:52:11 25 4
gpt4 key购买 nike

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

在 Startup.ConfigureServices() 我有:

services.AddIdentity<IdentityUser, IdentityRole>();

在我的类里面,我有:
public class Auth : IAuth
{
...
private readonly SignInManager<IdentityUser> _signInManager;

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

我得到了这个异常(exception):

An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore1[Microsoft.AspNetCore.Identity.IdentityUser]'
while attempting to activate
'Microsoft.AspNetCore.Identity.AspNetUserManager
1[Microsoft.AspNetCore.Identity.IdentityUser]'.



请注意,我什至没有引用通过的 SignInManager构造函数中的对象(我曾删除它以简化)。如果我删除 SignInManager来自构造函数的参数一切正常。

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

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

最佳答案

当您添加了身份时,您还没有配置任何数据存储。来自 docs你应该做这样的事情:

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

但是,如果您使用的是 ASP.Net Core 2.1,请使用较新的版本:
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();

关于c# - ASP.NET Core 2 的 SignInManager 依赖注入(inject)失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52502581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com