Orchard CMS中的Work <>类是什么?

ViR*_*iTy 2 c# orchardcms

简单明了,Orchard.Environment.Work<>该类定义的用例是Orchard\Environment\WorkContextModule.cs什么?

它可以在几个地方找到

private readonly Work<IContainerService> _containerService;

public Shapes(Work<IContainerService> containerService) {
  _containerService = containerService;
...
Run Code Online (Sandbox Code Playgroud)

这是为了延迟解决IContainerService

dev*_*qon 6

Work班是延迟加载依赖注入.实例化类时,依赖性未得到解决,但仅在调用Value属性时才解决:

private readonly IMyService _myService;
private readonly IMyOtherService _myOtherService;
public MyClass(Work<IMyService> myService, IMyOtherService myOtherService) {
    // Just assign the Work class to the backing property
    // The dependency won't be resolved until '_myService.Value' is called
    _myService = myService;
    // The IMyOtherService is resolved and assigned to the _myOtherService property
    _myOtherService = myOtherService;
}
Run Code Online (Sandbox Code Playgroud)

现在只有在_myService.Value被调用时,依赖性解析器才能解析IMyService,这使您可以进行延迟加载依赖注入.

  • 还有另一个区别 - 每次调用`Work <T> .Value`属性都会导致从Autofac容器中解析一个对象,而多次调用`Lazy <T> .Value`最多只执行一次. (5认同)
  • 它比延迟加载多一点.只需注入`Lazy <T>`就可以实现延迟加载.`Work <T>`类似,但它也确保从当前工作范围解析对象,无论请求者在什么范围内. (3认同)