Is it wrong to use an IoC container inside a Factory template? eg:
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 }
The reason I created the Factory method is because some of my IDialogViewModel implementations have a lot of parameters in their constructor, and every dialog must have a new UnitOfWork when creating the instance.
Here is how I use it:
public class PeopleMainViewModel : NotificationObject, ... { private readonly IDialogService _dialogService = null; public PeopleMainViewModel(IDialogService dialogService) { _dialogService = dialogService; }
Jalal source share