如何防止用户控件共享视图模型?
让我尝试解释一下我的问题。
我在 ASP.NET Web 窗体应用程序中使用 MVVM 模式。
每个用户控件都有一个支持 ViewModel,我使用以下方法初始化它们:
public TViewModelInterface ViewModel {
get {
return IoC.Resolve<TViewModelInterface>();
}
}
此代码存在于 ViewBase 类中,声明如下:
public abstract class ViewBase<TUserControl, TViewInterface, TViewModelInterface> : UserControl, IView
where TUserControl : UserControl
where TViewInterface : class, IView
where TViewModelInterface : class, IViewModel {
现在,只要 UserControl 不在同一 ASPX 页面中的多个位置使用,一切都很好。
完成后,砰!两个 UserControl 实例共享相同的 TViewModelInterface 实例!
到目前为止,我对视图模型接口使用每个请求初始化策略。我正在考虑将其设置为瞬态并将实例缓存在 ViewBase 内(因此本质上是在 UserControl 实例内)。
这是最好的方法吗?我希望我的问题说清楚了。
PS:IoC.Resolve 只是 Unity 的包装。
Let me try and explain my problem.
I am using an MVVM pattern in an ASP.NET Web Forms application.
Each usercontrol has a backing ViewModel and I am initializing them using:
public TViewModelInterface ViewModel {
get {
return IoC.Resolve<TViewModelInterface>();
}
}
This code is present inside a ViewBase class declared like so:
public abstract class ViewBase<TUserControl, TViewInterface, TViewModelInterface> : UserControl, IView
where TUserControl : UserControl
where TViewInterface : class, IView
where TViewModelInterface : class, IViewModel {
Now, it's all nice and fine as long as the UserControl is not used at multiple places in the same ASPX page.
When that is done, bam! Both the UserControl instances share the same TViewModelInterface instance!
Till now I was using Per Request init strategy for the View Model interfaces. I am thinking of making it Transient and caching the instance inside the ViewBase (so essentially inside a UserControl instance.)
Is that the best approach? I hope I made my question clear.
PS: IoC.Resolve is just a wrapper over Unity.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解正确的话,这只是适当配置依赖容器的问题。您似乎以单例模式进行解析,该模式为每个
Resolve
查询生成相同的实例。可以选择以多实例或大量其他模式来解析 - 例如,每个查询生成一个新实例。干杯,
保罗
If I understand correctly, this is only a question of configuring your dependency container appropriately. You seem to resolve in sort of singleton mode which yields same instance for each
Resolve<TViewModelInterface>
query. There are choices to resolve in multiton or a plethora of other modi - yielding a new instance per query, for example.Cheers,
Paul