ASP.NET MVC扩展UserManager遇CS0308错误求助
解决MyManager注入时CS0308错误的方案
错误核心原因
你创建的MyManager类是非泛型定义,但注入时却试图将它当作泛型类(MyManager<ApplicationUser>)使用,编译器因此抛出类型不匹配的错误。
修复步骤
1. 修正MyManager类的定义
根据你的需求选择以下两种定义方式之一:
方式一:泛型类(支持任意继承IdentityUser的用户类型)
public class MyManager<TUser> : UserManager<TUser> where TUser : ApplicationUser { public MyManager(IUserStore<TUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<TUser> passwordHasher, IEnumerable<IUserValidator<TUser>> userValidators, IEnumerable<IPasswordValidator<TUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TUser>> logger) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger) { // 自定义扩展逻辑 } }
方式二:非泛型类(仅针对ApplicationUser)
public class MyManager : UserManager<ApplicationUser> { public MyManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger) { // 自定义扩展逻辑 } }
2. 匹配Program.cs中的服务注册
- 若使用泛型MyManager,注册时需指定泛型参数:
builder.Services.AddScoped<MyManager<ApplicationUser>>();
- 若使用非泛型MyManager,直接注册类即可:
builder.Services.AddScoped<MyManager>();
3. 控制器中正确注入
- 泛型类注入方式:
public class HomeController : Controller { private readonly MyManager<ApplicationUser> _myManager; public HomeController(MyManager<ApplicationUser> myManager) { _myManager = myManager; } }
- 非泛型类注入方式:
public class HomeController : Controller { private readonly MyManager _myManager; public HomeController(MyManager myManager) { _myManager = myManager; } }
额外优化方案
如果需要替换系统默认的UserManager<ApplicationUser>,可以在Identity注册时直接指定自定义类:
builder.Services.AddIdentity<ApplicationUser, IdentityRole>() .AddUserManager<MyManager<ApplicationUser>>() .AddEntityFrameworkStores<ApplicationDbContext>();
这种情况下,控制器中直接注入UserManager<ApplicationUser>,实际获取的就是MyManager<ApplicationUser>的实例。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

