Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func<Owned<T>> vs Func<T> dependency

I know that Func<T> is different from Func<Owned<T>> and I know how to inject a dependency of each type. However, I often get confused as in when shall I prefer one over the other?

Assume, I have an application following MVP pattern and I want to inject a view PrintView. Then, on what grounds shall I decide that I should inject the view as Func<PrintView> or Func<Owned<PrintView>>?

like image 747
Gaurav Gahlot Avatar asked Feb 01 '17 15:02

Gaurav Gahlot


1 Answers

Func<T> will resolve an item from the lifetime scope that will be disposed when the lifetime scope is released. In the case of, say, an MVC controller:

  • Controller gets resolved from the request lifetime scope.
  • Calling the Func<T> will resolve a T from the request lifetime scope.
  • When the request lifetime scope is disposed, the controller and any T instances will be disposed with the request scope.

Owned<T> means you are explicitly taking responsibility for disposal of the T instance. Func<Owned<T>> will get an Owned<T> from the lifetime scope.

  • Controller gets resolved from the request lifetime scope.
  • Calling the Func<Owned<T>> will resolve an Owned<T> from the request lifetime scope.
  • When the request lifetime scope is disposed, the controller is disposed but Owned<T> instances are not disposed. You would need to do that yourself in some sort of cleanup in the controller or elsewhere in your application code.

Owned<T> is really only interesting if you want to take control over the time at which things get disposed. If you don't care or want the lifetime scope disposal to take care of it for you, it's not interesting.

like image 77
Travis Illig Avatar answered Oct 21 '22 21:10

Travis Illig