2

Plain and simple, what is the use case of the Orchard.Environment.Work<> class defined in Orchard\Environment\WorkContextModule.cs?

It can be found in several places like

private readonly Work<IContainerService> _containerService;

public Shapes(Work<IContainerService> containerService) {
  _containerService = containerService;
...

Is it for delayed resolution of IContainerService?

ViRuSTriNiTy
  • 5,017
  • 2
  • 32
  • 58

1 Answers1

6

The Work class is for lazy loading dependency injection. The dependency is not resolved when instantiating the class, but only when calling the Value property:

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;
}

Now only when _myService.Value is called, the IMyService gets resolved by the Dependency resolver, which gives you the working of a lazy loading dependency injection.

devqon
  • 13,818
  • 2
  • 30
  • 45
  • Thank you, exactly what i was assuming. – ViRuSTriNiTy Mar 30 '16 at 12:11
  • 3
    It's a bit more than lazy loading. Lazy loading can be achieved by simply injecting `Lazy`. `Work` is similar, but it also ensures that the object is resolved from the current work scope, no matter what scope the requestor is in. – Piotr Szmyd Mar 30 '16 at 12:33
  • 5
    There is also another difference - each call to `Work.Value` property will result in resolving an object from Autofac container, whereas calling `Lazy.Value` multiple times will do it at most once. – Piotr Szmyd Mar 30 '16 at 12:42