问题
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 aT
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 anOwned<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