Func> vs Func dependency

2019-06-23 22:03发布

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>>?

1条回答
爷的心禁止访问
2楼-- · 2019-06-23 22:34

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.

查看更多
登录 后发表回答