2012-11-19 36 views
4

在Factory Pattern中使用IoC容器是不好的做法嗎?例如:在抽象工廠模式中使用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 
} 

,我創建了一個工廠方法是bacause我的一些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) 
     { 
      //... 
     } 
    } 
} 

回答

2

你,你應該儘量避免IoC容器注入到一個工廠,而不是看,如果你的IoC框架可以生成工廠爲您服務。然而,這並不總是可行的,在這種情況下,我認爲在工廠中使用容器是可以接受的,只要它永遠不會逃脫。

就我個人而言,我不會把容器放在服務中(就像上面那樣),因爲它對我來說感覺像是類現在有兩個責任,並且注入框架已經逃脫到應用程序邏輯中。