0

我在我的 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")));

当我更改或其他内容TransientLifetimeManagerPerRequestLifetimeManager,会发生以下异常:

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

1 回答 1

0

在这一行可能会抛出异常:

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

这条线是有问题的,当unity真正解决一个IUnitOfWork(可能是另一个请求)时,IDbContext这里解决的对象已经被破坏了。

尝试:

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

这告诉容器:

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

于 2015-07-12T13:53:01.560 回答