Using Autofac with ASP.NET and the MVP pattern

早过忘川 提交于 2019-12-01 13:17:19

There is a better way. First, enable the Web integration module. This will enable automatic property injection into the Page instance.

Since your presenter needs the view in its constructor, your page should take a dependency on a presenter factory instead of the presenter itself.

So, first you need the presenter factory, which is a delegate with the necessary parameters:

public delegate IOCTestPresenter IOCTestPresenterFactory(IIOCTestView view);

This delegate must match the parameters (type and name) of the presenter constructor:

public class IOCTestPresenter
{
     public IOCTestPresenter(IIOCTestView view)
     {
     }
}

In your view, add a property receiving the factory delegate, and use the delegate to create the presenter:

public partial class IOCTest
{
     public IOCTestPresenterFactory PresenterFactory {get;set;}

     protected void Page_Load(object sender, EventArgs e)    
     {
           var presenter = PresenterFactory(this);
     }
}

In your container setup you will have to make the following registrations:

builder.Register<IOCTestPresenter>().FactoryScoped();
builder.RegisterGeneratedFactory<IOCTestPresenterFactory>();

I figured out a solution. Basically, you would register the page instance during the Page_PreInit event and then call the container to inject the dependencies. Ex.

public partial class IOCTest : System.Web.UI.Page, IIOCTestView
{

    protected void Page_PreInit(object sender, EventArgs e)
    {
        var containerProviderAccessor = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
        var containerProvider = containerProviderAccessor.ContainerProvider;

        var builder = new ContainerBuilder();
        builder.Register(this).ExternallyOwned().As<IIOCTestView>();

        builder.Build(containerProvider.RequestContainer);

        containerProvider.RequestContainer.InjectProperties(this);
    }

    public IOCTestPresenter Presenter { get; set; }

I'm not sure if there is a better way, but this seems to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!