You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC依赖注入报错:无法构造CartRepository服务

依赖注入错误:无法解析UserManager<IdentityUser>服务

错误信息

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: BookShoppingCartMvcUI.Repositories.ICartRepository Lifetime: Scoped ImplementationType: BookShoppingCartMvcUI.Repositories.CartRepository': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'BookShoppingCartMvcUI.Repositories.CartRepository'.)' InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'BookShoppingCartMvcUI.Repositories.CartRepository'.

问题根源

项目中自定义了ApplicationUser作为Identity用户类,且通过AddDefaultIdentity<ApplicationUser>注册身份服务,DI容器中实际注册的是UserManager<ApplicationUser>,但CartRepository的构造函数依赖的是UserManager<IdentityUser>,容器找不到对应服务导致解析失败。同时Startup.cs中手动注册UserManager<ApplicationUser>属于多余操作,可能引发冲突。

解决方案

1. 修改CartRepository的依赖类型

将构造函数中的UserManager<IdentityUser>替换为UserManager<ApplicationUser>:

public class CartRepository : ICartRepository
{
    private readonly ApplicationDbContext _db;
    private readonly UserManager<ApplicationUser> _userManager;

    public CartRepository(ApplicationDbContext db,
        UserManager<ApplicationUser> userManager)
    {
        _db = db;
        _userManager = userManager;
    }

    // 实现接口方法...
}

2. 移除Startup.cs中多余的服务注册

删除ConfigureServices方法中的以下代码:

services.AddScoped<UserManager<ApplicationUser>>();

修改后的Startup.cs代码片段:

public void ConfigureServices(IServiceCollection services)
{
    var connectionString = Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseNpgsql(connectionString));

    services.AddDefaultIdentity<ApplicationUser>(options =>
        options.SignIn.RequireConfirmedAccount = false)
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

    services.AddDatabaseDeveloperPageExceptionFilter();
    services.AddHttpContextAccessor();

    services.AddScoped<ICartRepository, CartRepository>();

    services.AddControllersWithViews();
}

3. 确认ApplicationUser的继承关系

确保ApplicationUser正确继承IdentityUser,示例定义:

public class ApplicationUser : IdentityUser
{
    // 可添加自定义属性
}

完成以上修改后,DI容器即可正确解析UserManager<ApplicationUser>并注入到CartRepository,解决服务构造失败问题。

内容的提问来源于stack exchange,提问作者randomuser32323223

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 12:03:38