Prism 和 Unity - 防止自动创建类型

发布于 2025-01-06 07:43:10 字数 281 浏览 2 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心房敞 2025-01-13 07:43:10

为每个 ViewModel 定义一个接口,然后相应地注册它们。

public interface IViewModel
{
     List<IUser> Users { get; }
}

public class ViewModel : IViewModel
{
     List<IUser> Users { get; }
}

Container.RegisterType<IViewModel, ViewModel>();

在构造函数中,确保注入的是接口类型,而不是具体类型,因为 Unity 肯定会构造具体类型的实例,因为它是可解析的;而一个接口可以有 N 个实现。

此外,您的代码的构建应确保应用程序中需要存在的数据应来自服务,而不是 ViewModel。让你的 ViewModel 成为单例不应该是你的方法,通过服务代理数据。这样你的 ViewModel 就可以随意构建/销毁,你想要持久化的数据存在于其他地方。

Container.RegisterType<IService, Service>(new ContainerControlledLifetimeManager());
Container.RegisterType<IViewModel, ViewModel>();

...

public List<IUser> Users
{
     get { return Container.Resolve<IService>().GetUsers(); }
}

Define an interface for each of your ViewModels and then register them accordingly.

public interface IViewModel
{
     List<IUser> Users { get; }
}

public class ViewModel : IViewModel
{
     List<IUser> Users { get; }
}

Container.RegisterType<IViewModel, ViewModel>();

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.

Container.RegisterType<IService, Service>(new ContainerControlledLifetimeManager());
Container.RegisterType<IViewModel, ViewModel>();

...

public List<IUser> Users
{
     get { return Container.Resolve<IService>().GetUsers(); }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文