Prism 和 Unity - 防止自动创建类型
我正在使用 Prism 和 Unity 作为容器创建一个 WPF 应用程序。有几次,我对注册类型的顺序感到困惑,其中类型(ViewModel 到 View 构造函数)是在我未注册时由 Unity 自动创建的。然后我尝试使用 ContainerControlledLifetimeManager() 注册类型,并且认为我创建了一个单例。然而,自动创建意味着视图模型的多个实例。
除了不成为木偶并且不执行上述操作的明显解决方案之外,是否有一种方法可以防止 Unity 自动创建未注册类型并可能抛出异常?
I'm creating a WPF app using Prism and Unity as the container. A couple of times I've come unstuck with the order of registering types whereby a type (ViewModel into View constructor) has been auto created by Unity when I've not registered it. Then I've tried to register the type using ContainerControlledLifetimeManager() and thought I'd created a singleton. However the auto creation has meant multiple instances of the view model.
Besides the obvious solution of not being a muppet and not doing the above, is there a way to prevent Unity auto creating unregistered types and perhaps throwing an exception instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为每个 ViewModel 定义一个接口,然后相应地注册它们。
在构造函数中,确保注入的是接口类型,而不是具体类型,因为 Unity 肯定会构造具体类型的实例,因为它是可解析的;而一个接口可以有 N 个实现。
此外,您的代码的构建应确保应用程序中需要存在的数据应来自服务,而不是 ViewModel。让你的 ViewModel 成为单例不应该是你的方法,通过服务代理数据。这样你的 ViewModel 就可以随意构建/销毁,你想要持久化的数据存在于其他地方。
Define an interface for each of your ViewModels and then register them accordingly.
In your constructor make sure that the interface type is being injected, not the concrete type as Unity will certainly construct an instance of a concrete type since it is resolvable; whereas an interface can have N implementations.
In addition, your code should be constructed in that the data that needs to exist across the application should come form a service, not the ViewModel. Making your ViewModel a singleton should not be your approach, proxy the data through a service. this way your ViewModel can be constructed/destroyed at will, the data you want persisted exists elsewhere.