【问题标题】:DI of a service used by many different ViewModels许多不同 ViewModel 使用的服务的 DI
【发布时间】:2013-06-29 20:10:00
【问题描述】:

我有一个 ViewManager 用于管理我的视图。它被放置在 App.View 命名空间中,并实现了一个 IViewManager 接口,放置在 App.ViewModel 库中。

问题是这个类被许多 ViewModel 使用,因为它们中的许多需要显示另一个 View。所以我需要在许多 ViewModel 中对 ViewManager 进行 ctor-inject,但其中一些需要创建一个工厂,所以我的问题是:

  • 这是正常问题还是我在某些方面有问题?
  • 新的 ViewModel 是否应该从 ShellViewModel 接收 ViewManager 例如:var newVM = ViewModelFactory.Create(this.ViewManager, ...) (其中“this”是 ShellViewModel) 还是来自工厂? 例如:var newVM = ViewModelFactory.Create(...) (这意味着 ViewManager 是由容器注入到 Factory 中的)?

感谢大家的帮助!

编辑

namespace BM.ViewModel
{
    public interface IViewManager
    {
        void Register<TViewInterface, TViewImplementation>(bool reset = false)
            where TViewInterface : IView
            where TViewImplementation : TViewInterface;

        void Unregister<TView>()
            where TView : IView;

        void UnregisterAll();

        TView GetView<TView>(BaseViewModel viewModel)
            where TView : IView;

        IEnumerable<IView> GetViews(BaseViewModel viewModel);

        IEnumerable<IView> GetAllViews();

        void CloseViews<TView>()
            where TView : IView;

        void CloseViews(BaseViewModel viewModel);


        void CloseAllViews();
    }
}

【问题讨论】:

    标签: .net mvvm dependency-injection inversion-of-control


    【解决方案1】:

    一切似乎都很好,您正在注入依赖项并使用工厂,这些都是很好的做法。

    关于ViewManager 实例,如果 ViewManager 是单例的——无论如何访问它——使用工厂或任何其他对 ViewManager 的引用都必须返回相同的实例。而且我不明白为什么要保留许多 ViewManager 实例,但这取决于您的特定应用程序设计。所以请分享IViewManager 接口声明并为每种方法提供一些cmets,以便清楚IViewManager 是否应该是单例。

    需要注意的几点

    • ViewManager 是无状态的吗?
    • 是否有任何功能要求 ViewManager 保留对所有 View 实例的引用?

    【讨论】:

    • 嗨,sll,谢谢您的回复。好吧,我是一名学生,我正在尝试学习 MVVM。因此,非常欢迎任何提示! =) 无论如何,我将使用我创建的 IViewManager 界面编辑主帖。我没有使用很多它的实例,但它必须传递给几乎每个 ViewModel。我的疑问是最好将其注入工厂或将其从 ShellViewModel 作为参数传递给 factory.Create() 函数。谢谢你的耐心!!附言该类不是单例,我应该在接口中添加一个 IViewManager 类型的属性并通过它访问实例吗?
    • 这似乎是一个Repiository 模式实现。 (C# example)。至少您可以将此接口 (ISP) 拆分为两个,其中一个将是 IViewRepository,除了 3 个 CloseViews() 方法和另一个类似 IViewCloser 的方法之外的所有方法(抱歉,坏名找不到合适的一)。
    • 谢谢!我现在来看看你链接的内容。无论如何,在您看来,这是一个好的解决方案,有没有更好的解决方案,有没有缺点?再次感谢您!
    • 只是问题,谁应该将 ViewManager 实例提供给新的 ViewModel? Factory 类(IoCC -> Factory -> newVM)还是 ShellViewModel? (IoCC -> ShellViewModel -> newVM)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    相关资源
    最近更新 更多