Asp.net mvc 3 将Unity.Mvc3与HierarchyCallifeTimeManager和工作单元模式一起使用不再延迟加载

Asp.net mvc 3 将Unity.Mvc3与HierarchyCallifeTimeManager和工作单元模式一起使用不再延迟加载,asp.net-mvc-3,entity-framework,dependency-injection,entity-framework-4.1,unity-container,Asp.net Mvc 3,Entity Framework,Dependency Injection,Entity Framework 4.1,Unity Container,首先,我的UoW继承自DbContext 我转而使用Unity.Mvc3,并将这一行添加到我的注册中: Container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager()); 在调用Cre之前,先在上下文中加载卫星 //Process Service public ProcessDto Create(ProcessDto dto) { var process

首先,我的UoW继承自DbContext

我转而使用Unity.Mvc3,并将这一行添加到我的注册中:

Container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
在调用Cre之前,先在上下文中加载卫星

//Process Service
    public ProcessDto Create(ProcessDto dto)
    {
       var processEntity = new Process(){StatusId = dto.StatusId}
       processRepository.Add(processEntity)
       unitOfWork.Commit()
       //at this point, before using Unity.Mvc3 the Status would be proxied into the   processEntity. Moving to Unity.Mvc3 it is like Lazy Loading stopped working.
       return Mapper.Map<Process,ProcessDto>(processEntity);
    }
//进程服务
要创建的公共进程(进程到进程)
{
var processEntity=new Process(){StatusId=dto.StatusId}
processRepository.Add(processEntity)
unitOfWork.Commit()
//此时,在使用Unity.Mvc3之前,状态将被代理到processEntity中。移动到Unity.Mvc3就像延迟加载停止工作一样。
返回Mapper.Map(processEntity);
}

单步执行代码直到Create调用之后,请求才会终止。不确定是否有人遇到过类似的情况。

您的
状态
属性不是虚拟的,因此无法代理该实体进行延迟加载,Unity或任何其他IoC容器对此没有影响


此外,您还直接使用
Process
构造函数-如果您创建了Process实例,它将无法被代理,延迟加载也无法工作。您必须在
DbSet
上使用
Create
factory方法来获取代理实体。

我没有在这个示例中设置虚拟实体,但我可以向您保证,它们实际上是在我的模型中设置的。我将更新我的示例。关于您对流程构造函数的评论,正如我上面所说的,当我返回使用Microsoft Unity resolver并删除Unity.MVC3版本时,状态实际上会出现。您的
processEntity
工作时是什么类型(真正的运行时类型)?它是流程实体类型。同上。你在那里看到的一切都与我的设置相同。唯一的区别是使用Unity.MVC3解析器。这就像UoW在某个时候被丢弃一样。好的。我明白为什么它现在起作用了。我忽略了这一点:在调用Create之前,satues是在上下文中加载的,因此不会一直延迟加载,因为加载了数据。在调用Create之前,satues是上下文的一部分。因此,在我在Create方法中提交之后,EF会提取状态的FKs,将它们加载到流程实体中。但是,只有当我使用“开箱即用”的Unity解析器时。真奇怪。
//Process Service
    public ProcessDto Create(ProcessDto dto)
    {
       var processEntity = new Process(){StatusId = dto.StatusId}
       processRepository.Add(processEntity)
       unitOfWork.Commit()
       //at this point, before using Unity.Mvc3 the Status would be proxied into the   processEntity. Moving to Unity.Mvc3 it is like Lazy Loading stopped working.
       return Mapper.Map<Process,ProcessDto>(processEntity);
    }