gpt4 book ai didi

c# - 在主 ViewModel 中引入对 DI 容器的引用是设计缺陷吗?

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:52 24 4
gpt4 key购买 nike

我有以下内容

  • ViewModels:MainWindowViewModelBaseProjectViewModelTextFileProjectViewModelSpreadsheetProjectViewModel(TextFileProjectViewModel, SpreadsheetProjectViewModel继承自BaseProjectViewModel)

  • 服务:

    FileDIalogService : IFileDialogService
    消息框服务:IMessageBoxService
    ModalDialogFactory : IModalDialogFactory
    ModalDialogService : IModalDialogservice

MainWindowViewModel 具有以下构造函数:

public MainWindowViewModel( IModalDialogService     modalDialogService,
IModalDialogFactory modalDialogFactory,
IMessageBoxService messageBoxService,
IFileDialogService fileDialogService)
{
_modalDialogService = modalDialogService;
_modalDialogFactory = modalDialogFactory;
_messageBoxService = messageBoxService;
_fileDialogService = fileDialogService;
}

在 App.xaml 中我不使用 StartupUri。

目前在 App.xaml.cs 中我手动进行引导:

    MainWindow mainWindow = new MainWindow();
mainWindow.DataContext = new MainWindowViewModel(new ModalDialogService(), new ModalDialogFactory(), new MessageBoxService(), new FileDialogService());
mainWindow.Show();

我知道我可以使用容器(比如 Unity)来做:

IUnityContainer container = new UnityContainer();

container.RegisterType<IModalDialogService, ModalDialogService>(new ContainerControlledLifetimeManager());
/* ... and so on for each service interface and its appropriate implementation... */

MainWindow mainWindow = new MainWindow();
mainWindow.DataContext = container.Resolve<MainWindowViewModel>();
mainWindow.Show();

在另一个问题中,我了解到我可以更进一步,将 IModalDialogFactory 实现为自动工厂并注入(inject) ...

但是我意识到我遗漏了一件重要的事情:

当我需要 TextFileProjectViewModelSpreadsheetProjectViewModel 中的那些服务时,它们是在 MainWindowViewModel 中创建的,我需要手动将引用注入(inject)它们.
我在某处读到,从设计的角度来看,将容器引入 MainWindowViewModel 是一件坏事,因为它会产生不必要的依赖性。但是我不知道如何使用 DI 容器(任何容器,不仅仅是 Unity)来解析 MainWindowViewModel 中的其他 View 模型,而无需在 MainWindowViewModel 中保留引用。< br/>

我是不是遗漏了什么或者我是否犯了设计/架构错误?

最佳答案

我提前为对 xaml 领域了解不多而道歉,但希望这对您有所帮助。

在极端情况下,您必须选择适当的 DI 以外的东西。最好的情况通常是构造函数注入(inject)。

“严格遵守构造函数注入(inject)可以很容易地看出何时违反了 SRP 并且应该重构为 Facade 服务。” - http://blog.ploeh.dk/2010/02/02/RefactoringtoAggregateServices

对于那些抽象工厂,引用 DI 容器或 Service Locator是我能想到的最接近解耦的东西。

Service locator an anti pattern?

就是说,什么在构造您的 ViewModel,您能否将这种依赖关系推得足够远,以至于您的 DI composition root可以用吗?

关于c# - 在主 ViewModel 中引入对 DI 容器的引用是设计缺陷吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17494916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com