简体   繁体   中英

Register a Presenter with a View

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>(); ????

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM