Unity 返回新的服务实例
我在使用 Unity 和 WPF 时遇到了一些问题。场景是我有一个遵循 MVVM 设计模式的 WPF 应用程序。 A 有一个名为 ViewKDI 的模块。在这个模块中,我有一个名为 ViewKDIService 的服务,ViewKDIService 服务使用另一个名为 UserService 的服务。
每次加载 ViewKDI 模块时,我都希望 Unity 返回 ViewKDIService 和 UserService 的新实例。
我已将以下内容放入 shell 引导程序中:
Container.RegisterType<IUserService, UserService>();
在 ViewKDI 模块中,我已放入以下内容:
Container.RegisterType<IViewKDIService, ViewKDIService>();
每次 ViewKDI 模块加载时,都会调用 ViewKDIService 构造函数。但是 UserService 构造函数仅在第一次被调用,这意味着我没有获得 UserService 的新实例。
我也需要 Unity 为我提供一个新的 UserService 实例,以便我可以与应用程序的其余部分分开管理此会话。
有什么想法吗?
谢谢 费萨尔
I have come across a bit of a problem while using Unity and WPF. The scenario is I have a WPF application which follows the MVVM design pattern. A have a module called ViewKDI. Within this module I have a service called ViewKDIService, the ViewKDIService service utilises another service called UserService.
Every time I load the module ViewKDI I want Unity to return me a new instance of both the ViewKDIService and the UserService.
I have put the below in the shell bootstrapper:
Container.RegisterType<IUserService, UserService>();
In the ViewKDI module I have put the following:
Container.RegisterType<IViewKDIService, ViewKDIService>();
Each time the ViewKDI module loads the ViewKDIService constructor is called. However the UserService constructor is only called the first time, this means that I am not getting a new instance of UserService.
I require unity to give me a new instance of UserService too so that I can manage this session separately from the rest of the application.
Any ideas?
Thanks
Faisal
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Unity 的默认行为是每次请求时为每个对象创建一个新实例,因此您不应该看到这种行为。
根据我从源代码和 MSDN 文档中收集到的信息(this是一本好书),您可以在注册类型时指定一个“生命周期管理器”对象,以告诉 Unity 应如何构造和缓存该类型。使用 TransientLifetimeManager(本质上不进行缓存)将导致 Unity 每次都重新创建该类。所以试试这个:
... 看看它是否每次都会创建一个新的 UserService 。
Unity's default behaviour is to create a new instance of each object each time one is requested, so you shouldn't be seeing this behaviour.
From what I can gather from the source code and MSDN documentation (this is a good read), you can specify a "lifetime manager" object when you register a type to tell Unity how the type should be constructed and cached. Using the TransientLifetimeManager (which essentially does no caching) will cause Unity to re-create the class each time. So try this:
... and see if it creates a new UserService each time.