4
팩토리 패턴에서 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
}
내 IDialogViewModel 구현 중 일부는 자신의 생성자에 매개 변수를 많이 가지고 인스턴스화 할 때 또한, 각 대화가 새로운 UnitOfWork에 있어야합니다 bacause 팩토리 메소드가 생성 된 이유. 당신이 대신 IOC의 프레임 워크는 당신을위한 공장을 생성 할 수있는 경우를 보면, 공장으로 IoC 컨테이너를 주입 피하려고한다
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)
{
//...
}
}
}