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

半城伤御伤魂 提交于 2019-12-23 14:19:09

问题


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:


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.



来源:https://stackoverflow.com/questions/41984172/funcownedt-vs-funct-dependency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!