ASP.NET MVC中使用Simple Injector注册IUserStore<ApplicationUser>报错求助
你碰到的这两个错误其实是用Simple Injector整合ASP.NET Identity时的典型坑,我来一步步帮你理清解决思路:
第一个错误的原因
System.InvalidOperationException提示你ApplicationUserManager的构造函数里的store参数(类型IUserStore<ApplicationUser>)没注册,这是因为Simple Injector不知道该用哪个具体类来实现这个接口——ASP.NET Identity默认提供了UserStore<ApplicationUser>作为IUserStore<ApplicationUser>的实现类,但你没告诉容器这层映射关系。
第二个错误的原因
你尝试的container.Register<IUserStore<ApplicationUser>>()之所以报错,是因为Simple Injector的这个Register<T>()重载要求T是具体类(可以直接实例化的类型),而IUserStore<ApplicationUser>是接口,不能直接实例化,所以得用另一个重载来指定接口和实现类的映射。
正确的解决步骤
1. 确保依赖包齐全
首先确认你的项目已经安装了以下NuGet包:
- SimpleInjector
- SimpleInjector.Integration.Web.Mvc
- Microsoft.AspNet.Identity.EntityFramework(
UserStore就在这个包里)
2. 注册DbContext
UserStore<ApplicationUser>的构造函数依赖你的ApplicationDbContext,所以首先要把DbContext注册为Scoped生命周期(每个请求一个实例,符合Identity的使用场景):
container.Register<ApplicationDbContext>(Lifestyle.Scoped);
3. 注册IUserStore与实现类的映射
用Register<TService, TImplementation>()重载来注册接口和具体实现的关系,同样指定Scoped生命周期:
container.Register<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(Lifestyle.Scoped);
4. 注册ApplicationUserManager
把ApplicationUserManager也注册为Scoped生命周期,确保它的依赖(也就是刚才注册的IUserStore<ApplicationUser>)能被正确注入:
container.Register<ApplicationUserManager>(Lifestyle.Scoped);
5. 可选:配置ApplicationUserManager的初始化规则
如果需要设置密码验证、用户名验证等规则,可以用RegisterInitializer来初始化:
container.RegisterInitializer<ApplicationUserManager>(manager => { // 用户名验证规则 manager.UserValidator = new UserValidator<ApplicationUser>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // 密码验证规则 manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = false, // 根据你的需求调整其他规则 }; });
6. 完成容器配置并绑定到MVC
最后别忘了注册MVC控制器和过滤器,验证容器配置,再把Simple Injector设置为MVC的依赖解析器:
// 设置默认的Scoped生命周期(ASP.NET MVC 5推荐用AsyncScopedLifestyle) container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); container.RegisterMvcControllers(Assembly.GetExecutingAssembly()); container.RegisterMvcIntegratedFilterProvider(); // 验证容器配置是否正确 container.Verify(); // 替换MVC的默认依赖解析器 DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
检查ApplicationUserManager的构造函数
还要确保你的ApplicationUserManager构造函数是正确的,应该继承自UserManager<ApplicationUser>并接收IUserStore<ApplicationUser>参数:
public class ApplicationUserManager : UserManager<ApplicationUser> { public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) { } // 其他自定义代码... }
这样配置完之后,容器就能正确解析ApplicationUserManager的依赖,不会再出现之前的错误了。
内容的提问来源于stack exchange,提问作者Aishlinn

