Web API中Unity用PerRequestLifetimeManager注册DbContext时抛异常求助
问题分析与解决方案
你遇到的这个异常核心原因很明确:你在应用启动阶段(还没有任何HTTP请求进来的时候)就尝试解析使用PerRequestLifetimeManager注册的DbContext了。
看你注册IRepository<Country>和IRepository<Region>的代码,你直接在InjectionConstructor里调用了container.Resolve(typeof(DbContext),"MyContext")——这行代码会在RegisterTypes执行时(也就是应用启动初始化阶段)立刻触发DbContext的解析,但此时还没有HTTP请求上下文,而PerRequestLifetimeManager的生命周期完全依赖HTTP请求上下文,自然就抛出了那个错误。
修复步骤
1. 改用ResolvedParameter延迟解析
不要直接在注册时调用Resolve,而是告诉Unity在需要的时候再去解析对应的DbContext,把InjectionConstructor的参数换成ResolvedParameter:
container .AddNewExtension<Interception>() .RegisterType(typeof(DbContext), typeof(MyDbContext), "MyContext", new PerRequestLifetimeManager()) // 修改Repository的注册方式,用ResolvedParameter延迟解析 .RegisterType(typeof(IRepository<Country>), typeof(Repository<Country>), new InjectionConstructor(new ResolvedParameter(typeof(DbContext), "MyContext"))) .RegisterType(typeof(IRepository<Region>), typeof(Repository<Region>), new InjectionConstructor(new ResolvedParameter(typeof(DbContext), "MyContext")));
2. (可选)让Unity自动匹配构造函数
如果你的Repository<T>类的构造函数只有一个DbContext类型的参数,并且参数名称或者类型能和你注册的DbContext匹配,你甚至可以省略InjectionConstructor,让Unity自动帮你注入:
container .AddNewExtension<Interception>() .RegisterType(typeof(DbContext), typeof(MyDbContext), "MyContext", new PerRequestLifetimeManager()) .RegisterType(typeof(IRepository<Country>), typeof(Repository<Country>)) .RegisterType(typeof(IRepository<Region>), typeof(Repository<Region>));
3. 确保Web API的Unity依赖解析器配置正确
检查你的WebApiConfig类(或者启动配置代码),是否已经把Unity设置为Web API的依赖解析器,这是PerRequestLifetimeManager正常工作的前提:
public static void Register(HttpConfiguration config) { // 其他Web API配置... // 初始化Unity容器 var container = new UnityContainer(); UnityConfig.RegisterTypes(container); // 设置Web API的依赖解析器 config.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container); }
额外注意点
- 绝对不要在应用启动阶段、后台线程或者非HTTP请求的场景下,解析使用
PerRequestLifetimeManager注册的服务,这些场景下没有HTTP请求上下文,必然会报错。 - 如果你有后台任务需要使用
DbContext,建议单独注册一个使用TransientLifetimeManager或者HierarchicalLifetimeManager的DbContext实例,和请求绑定的实例分开。
内容的提问来源于stack exchange,提问作者codermav
相关产品推荐
相关产品推荐

