对于 WindowsForms,我有一个单独的项目用于 IoC 的东西。我称之为CompositionRoot。
CompositionRoot
(启动项目)的入口点:
public static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
BootsTrapper.Boot();
using (var mainForm = ObjectFactory.GetInstance<IPresenter<IMainView>>())
{
Application.Run((Form)mainForm.CurrentView);
}
}
}
BootsTrapper
负责注册并且是CompositionRoot
.
MainViewPresenter 显示第一个表单。MainViewPresenter 可以通过使用IMainViewPresenterFacade
包含抽象 Presenter 工厂的外观服务来显示其他表单。
public class MainViewPresenter : Presenter<IMainView>
{
readonly IArticleRepository _articlesRepository;
readonly IMainViewPresenterFacade _presenterFactory;
readonly IUnitOfWork _unitOfWork;
public MainViewPresenter(IMainView currentView, IArticleRepository articlesRepository, IUnitOfWork unitOfWork,
IMainViewPresenterFacade presenterFactory)
: base(currentView, unitOfWork)
{
_articlesRepository = articlesRepository;
_unitOfWork = unitOfWork;
_presenterFactory = presenterFactory;
Ensure.That(articlesRepository).IsNotNull();
Ensure.That(presenterFactory).IsNotNull();
CurrentView.DetailsClick += View_DetailsClick;
CurrentView.CloseClick += ViewCloseClick;
CurrentView.CreateClick += View_CreateClick;
CurrentView.DeleteClick += View_DeleteClick;
CurrentView.BindModel(_articlesRepository.GetAll().Select(x => new ArticleViewModel { Id = x.ArticleId, Name = x.Description }));
}
public override void Dispose()
{
base.Dispose();
CurrentView.DetailsClick -= View_DetailsClick;
CurrentView.CloseClick -= ViewCloseClick;
CurrentView.CreateClick -= View_CreateClick;
CurrentView.DeleteClick -= View_DeleteClick;
}
void View_DeleteClick(object sender, EventArgs e)
{
var selectedArticle = CurrentView.GetSelectedArticle();
var article = _articlesRepository.GetById(selectedArticle.Id);
_articlesRepository.Delete(article);
_unitOfWork.Commit();
}
void View_CreateClick(object sender, EventArgs e)
{
using (var createPresenter = _presenterFactory.CreateCreatePresenter())
{
ShowDialog(createPresenter.CurrentView, CurrentView);
}
}
void ViewCloseClick(object sender, EventArgs e)
{
CurrentView.Close();
}
void View_DetailsClick(object sender, EventArgs eventArgs)
{
var article = CurrentView.GetSelectedArticle();
if (article == null) return;
using (var detailPresenter = _presenterFactory.CreateDetailPresenter(article))
{
ShowDialog(detailPresenter.CurrentView, CurrentView);
}
}
}
看看我的SimpleMVP项目或这个问题Dependency Injection and project structure for Console applications并随时提出更多问题 :)