簡體   English   中英

更改時出現Unity IoC無效操作,然后更改RegisterType中的生存期管理器

[英]Unity IoC Invalid Operation when change then lifetime manager in RegisterType

我在MVC 4項目中使用Unity對IoC進行了此配置。

container.RegisterType<IDbContext, ConstructionRepositoryContext>("ConstructionRepositoryContext", new TransientLifetimeManager());
container.RegisterType<IDbContext, GeneralRepositoryContext>("GeneralRepositoryContext", new TransientLifetimeManager());

container.RegisterType<IUnitOfWork, UnitOfWork>(
    "ConstructionUnitOfWork",
    new InjectionConstructor(container.Resolve<IDbContext>("ConstructionRepositoryContext")));

container.RegisterType<IUnitOfWork, UnitOfWork>(
    "GeneralUnitOfWork",
    new InjectionConstructor(container.Resolve<IDbContext>("GeneralRepositoryContext")));

當我通過PerRequestLifetimeManager或其他方法更改TransientLifetimeManager ,會發生以下異常:

(第101行中的錯誤)

Operation is not valid due to the current state of the object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Line 99:  new InjectionConstructor(container.Resolve<IDbContext>("ConstructionRepositoryContext")));
Line 100:
Line 101: container.RegisterType<IUnitOfWork, UnitOfWork>(
Line 102:   "GeneralUnitOfWork",
Line 103:   new InjectionConstructor(container.Resolve<IDbContext>("GeneralRepositoryContext")));

可能在此行拋出異常:

container.Resolve<IDbContext>("ConstructionRepositoryContext"))

這行是有問題的,在團結真正解決IUnitOfWork (可能是另一個請求)時,此處解決的IDbContext對象已被破壞。

嘗試:

container.RegisterType<IUnitOfWork, UnitOfWork>(
    "ConstructionUnitOfWork",
    new InjectionConstructor(new ResolvedParameter<IDbContext>("ConstructionRepositoryContext")));

這告訴容器:

使用名為"ConstructionUnitOfWork"名稱解析UnitOfWork時,請使用帶有單個IDbContext參數的構造函數,而在解析該參數時,請使用名稱"ConstructionRepositoryContext"解析

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM