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")));

当我将 TransientLifetimeManager 更改为 PerRequestLifetimeManager 或其他内容时,会发生以下异常:

(第 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"))

这一行是有问题的,当unity真正解析一个IUnitOfWork(可能是另一个请求)的时候,这里解析的IDbContext对象已经被销毁了

尝试:

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

这告诉容器:

在解析名为 "ConstructionUnitOfWork"UnitOfWork 时,使用带有单个 IDbContext 参数的构造函数,在解析该参数时,使用名称 "ConstructionRepositoryContext" 解析