【发布时间】:2018-03-03 09:40:17
【问题描述】:
我希望我的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>。你知道这是怎么回事吗? -
在 database 上下文中依赖用户管理器听起来不是一个好主意。您可能应该有一个服务,而不是依赖于数据库上下文和用户管理器。
-
@rory 您已经可以在应用程序上下文中访问
Users。使用当前请求的用户 ID 直接查询。根本不需要引用用户管理器。 -
UserManager<T>依赖于UserStore<T>,它依赖于使用 ASP.NET Core Identity 注册的数据库上下文,而这恰好是依赖于用户管理器的数据库上下文。 -
@rory 您还应该保持
ApplicationContext构造函数精简,不要尝试访问用户或在其中进行查询。提取用户并在目标方法中进行查询,因为届时请求将完全实现。它基本上应该只有_contextAccessor = contextAccessor;,其余的应该在其中一个crud操作上完成。
标签: c# asp.net-core dependency-injection circular-dependency asp.net-2.0