我希望我的
代码:
ApplicationContext
构造函数可以接受UserManager
作为参数,但我在依赖注入方面遇到了问题。代码:
public class ApplicationContext : IdentityDbContext<ApplicationUser>
{
private IHttpContextAccessor _contextAccessor { get; set; }
public ApplicationUser ApplicationUser { get; set; }
private UserManager<ApplicationUser> _userManager;
public ApplicationContext(DbContextOptions<ApplicationContext> options, IHttpContextAccessor contextAccessor, UserManager<ApplicationUser> userManager)
: base(options)
{
_contextAccessor = contextAccessor;
var user = _contextAccessor.HttpContext.User;
_userManager = userManager;
ApplicationUser = _userManager.Users.FirstOrDefault(u => u.Id == _userManager.GetUserId(user));
}
}
在startup.cs
中:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("RCI.App")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationContext>()
.AddDefaultTokenProviders();
services.AddAuthentication();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
services.AddOptions();
}
错误消息:
检测到类型为“Microsoft.AspNetCore.Identity.UserManager`1 [RCI.App.Models.ApplicationUser]”的服务存在循环依赖关系。
能否有人指出我做错了什么?
UserManager<ApplicationUser>
和ApplicationContext
具有明确的依赖关系,导致循环依赖。当解析ApplicationContext
时,它必须创建一个需要ApplicationContext
的UserManager<ApplicationUser>
。你能看出这会导致什么问题吗? - NkosiUserManager<T>
依赖于UserStore<T>
,而UserStore<T>
又依赖于在 ASP.NET Core Identity 中注册的数据库上下文,这恰好是您的数据库上下文,它又依赖于用户管理器。 - pokeApplicationContext
构造函数的简洁性,并且不要在其中尝试访问用户或进行查询。在目标方法中提取用户并进行查询,因为此时请求已经完全实现。它基本上只需要_contextAccessor = contextAccessor;
,其余操作应该在CRUD操作之一完成。 - Nkosi