Does unity just make clasess with out needing anything registered?

◇◆丶佛笑我妖孽 提交于 2019-12-02 13:21:42

问题


I am watching Mike Tautly's awesome intro to Prism. It was all making sense, but I got a bit confused in the sixth video.

He has his view class's constructor take a parameter of the ViewModel. He then says that unity will fill this in for us (ie construct it).

In the past he has had to register this kind of thing (ie IMyClass registered to MyClass). But he did not do that for the ViewModel.

The only difference I can see is that the dependency to the ViewModel was not an interface, but rather a direct class. Does unity see that and just try to construct the ViewModel or did I miss a step? (And if the ViewModel had parameters would it try to make those too?)


回答1:


When a type can be instantiated (i.e. not a base class nor an interface) unity can figure out how that type is created without the need of registering a type mapping.

Mappings are useful when the type to be injected is not instantiatable on its own.

I hope this helps.

Thanks, Damian




回答2:


Unity tries to construct the class injecting resolved dependencies in the biggest constructor (with the maximum number of parameter).

So, if you have such a view model:

public class ViewModel
{
    public ViewModel(IMyDependency dependency) { .. }
    ...
}

you only need to register IMyDependency.



来源:https://stackoverflow.com/questions/3836611/does-unity-just-make-clasess-with-out-needing-anything-registered

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