Func< Owned T> vs Func< T>依赖 [英] Func<Owned<T>> vs Func<T> dependency

查看:84
本文介绍了Func< Owned T> vs Func< T>依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Func<T>Func<Owned<T>>不同,并且我知道如何注入每种类型的依赖项.但是,我常常会感到困惑,例如何时才能选择一个?

假设,我有一个遵循MVP模式的应用程序,并且我想注入一个视图PrintView.然后,我应该基于什么理由决定将视图注入为Func<PrintView>还是Func<Owned<PrintView>>?

解决方案

Func<T>将从生存期范围中解析一个项目,该项目在发布生存期范围时将被处置.例如,对于MVC控制器:

  • 从请求生存期范围中解析控制器.
  • 调用Func<T>将在请求生存期范围内解析T.
  • 在放置请求生存期范围时,控制器和任何T实例将与请求范围一起放置.

Owned<T>表示您明确承担处置T实例的责任. Func<Owned<T>>将从生存期范围中获取Owned<T>.

  • 从请求生存期范围中解析控制器.
  • 调用Func<Owned<T>>将在请求生存期范围内解析Owned<T>.
  • 处理请求生存期范围时,将处理控制器,但将Owned<T>个实例不处理.您需要自己在控制器中或应用程序代码中的其他地方进行某种清理.

Owned<T>仅在您想控制事物处置的时间时才真正有趣.如果您不关心或希望终生范围处置为您照顾它,那就没意思了.

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

解决方案

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.

这篇关于Func&lt; Owned T&gt; vs Func&lt; T&gt;依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆