gpt4 book ai didi

c# - 在抽象工厂模式中使用 IoC?

转载 作者:行者123 更新时间:2023-11-30 12:31:28 25 4
gpt4 key购买 nike

在工厂模式中使用 IoC 容器是一种不好的做法吗?例如:

public interface IDialogService
{
void RegisterView<TView, TViewModel>(string viewName)
where TViewModel : IDialogViewModel
where TView : Window;

bool? ShowDialog(string viewName, IDialogViewModel viewModel);
// factory method:
TViewModel CreateDialogViewModel<TViewModel>(string name) where TViewModel : IDialogViewModel;
}

public class DialogService : IDialogService
{
private readonly IUnityContainer _container;
public DialogService(IUnityContainer container)
{
_container = container;
}

#region IDialogService Members

public void RegisterView<TView, TViewModel>()
where TView : Window
where TViewModel : IDialogViewModel
{
RegisterView<TView, TViewModel>("");
}

public void RegisterView<TView, TViewModel>(string viewName)
where TView : Window
where TViewModel : IDialogViewModel
{
if (!_container.IsRegistered<TViewModel>())
_container.RegisterType<TViewModel>();

if (string.IsNullOrEmpty(viewName))
{
viewName = typeof(TView).Name;
}
_container.RegisterType<Window, TView>(viewName);
}

public bool? ShowDialog(string viewName, IDialogViewModel viewModel)
{
var view = _container.Resolve<Window>(viewName);
view.DataContext = viewModel;
view.Owner = Application.Current.MainWindow;
return view.ShowDialog();
}
// factory method:
public TViewModel CreateDialogViewModel<TViewModel>(string name) where TViewModel : IDialogViewModel
{
return _container.Resolve<TViewModel>(name);
}

#endregion
}

我创建工厂方法的原因是因为我的一些 IDialogViewModel 实现在其构造函数中有很多参数,而且每个对话框在实例化时都必须有新的 UnitOfWork。

下面是我的使用方法:

public class PeopleMainViewModel : NotificationObject, ...
{
private readonly IDialogService _dialogService = null;
public PeopleMainViewModel(IDialogService dialogService)
{
_dialogService = dialogService;
}

// this method executes by a command.
public void AddPerson()
{
// here is factory method usage. each time PersonDialogViewModel instantiates, a new Unit of work will be created.
var viewModel = _dialogService.CreateDialogViewModel<PersonDialogViewModel>();

// this shows person dialog window to user...
var result = _dialogService.ShowDialog("PersonWindow", viewModel);
if(result == true)
{
//...
}
}
}

最佳答案

您应该尽量避免将 IoC 容器注入(inject)工厂,而是查看您的 IoC 框架是否可以为您生成工厂。然而,这并不总是可能的,在这些情况下,我认为在工厂中使用容器是可以接受的,只要它永远不会逃逸。

就我个人而言,我不会将容器放在服务中(如上例所示),因为在我看来类现在有两个职责并且注入(inject)框架已经逃逸到应用程序逻辑中。

关于c# - 在抽象工厂模式中使用 IoC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13453837/

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