Register a Presenter with a View

2019-05-26 05:36发布

If I have a presenter like this -

public class LandingPresenter : ILandingPresenter
{            
    private ILandingView _view { get; set; }
    private IProductService _productService { get; set; }

    public LandingPresenter(ILandingView view, IProductService)
    {
        ....
    }
}

How do I register this Presenter with Autofac considering the dependent view will not be registered (but IProductService will)

    builder.RegisterType<LandingPresenter>().As<ILandingPresenter>(); ????

标签: c# mvp autofac
1条回答
Evening l夕情丶
2楼-- · 2019-05-26 06:05

Why not register the views in the container as well, put Autofac to work! Then you can hook up presenters and views automagically by using constructor injection on the presenters and property injection on the views. You just have to register the views with property-wiring:

builder.RegisterAssemblyTypes(ThisAssembly).
    Where(x => x.Name.EndsWith("View")).
    PropertiesAutowired(PropertyWiringFlags.AllowCircularDependencies).
    AsImplementedInterfaces();

Presenter:

public class LandingPresenter : ILandingPresenter
{            
    private ILandingView _view;
    private IProductService _productService { get; set; }

    public LandingPresenter(ILandingView view, IProductService _productService)
    {
        ....
    }
}

View:

public class LandingView : UserControl, ILandingView
{
    // Constructor

    public LandingView(... other dependencies here ...)
    {
    }

    // This property will be set by Autofac
    public ILandingPresenter Presenter { get; set; }
}

And if you want to go view-first then you should be able to reverse it so the presenters take the view as property instead.

查看更多
登录 后发表回答