我在Web API应用程序中配置了Unity以注入依赖项,但是当我尝试向PerRequestLifetimeManager注册DbContext时,它抛出了一个异常。如果我使用默认的LifeTimeManager,它工作得很好。我已经在应用程序中添加了Unity.MVC和Unity.Webapi nuget包。以下是RegisterTypes的代码。
container
.AddNewExtension<Interception>()
.RegisterType(typeof(DbContext), typeof(MyDbContext), "MyContext", new PerRequestLifetimeManager())
.RegisterType(typeof(IRepository<Country>), typeof(Repository<Country>), new InjectionConstructor(container.Resolve(typeof(DbContext),"MyContext")))
.RegisterType(typeof(IRepository<Region>), typeof(Repository<Region>), new InjectionConstructor(container.Resolve(typeof(DbContext), "MyContext")))
当我运行应用程序时,它在RegisterTypes中抛出以下异常。
Unity.Exceptions.ResolutionFailedException...
内部异常1: InvalidOperationException: PerRequestLifetimeManager只能在HTTPASP.NET的上下文中使用。导致此错误的原因是在非request.Possible应用程序上使用生存期管理器,或者在未与相应同步上下文关联的线程中使用它。
你知道我做错了什么吗?
发布于 2018-06-10 06:53:54
我想通了。正如错误消息所说,在应用程序初始化时,我试图在非Http请求上下文中注入DbContext。如果我像下面这样做,它工作得很好,而不是试图在RegisterType中为存储库配置"InjectionConstructor“。它在每次请求时都会成功地在存储库中注入一个新的DbContext实例。对于使用"PerRequestLifetimeManager“注册的类型,似乎不能使用InjectionConstructor。
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>))
https://stackoverflow.com/questions/50320903
复制相似问题