标签:c ioc-container factory-pattern
在Factory Pattern中使用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容器注入工厂,而是查看您的IoC框架是否可以为您生成工厂.然而,这并不总是可行的,在那些情况下,我认为在工厂中使用容器是可以接受的,只要它永远不会逃脱.
我个人不会把容器放在一个服务中(如上所述),因为我觉得这个类现在有两个职责,注入框架已经转移到应用程序逻辑中.
标签:c,ioc-container,factory-pattern 来源: https://codeday.me/bug/20190704/1372967.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。