1

I am trying to add Autofac into my Webforms application (MVP pattern).

I have a problem with property injection. At the moment the Presenter property is instantiated with a brand new instance of the View class. That causes a null reference exception when 'view.Text' is set inside Presenter's constructor.

How can I configure autofac to instantiate Presenter with the instance of the parent View object?

public interface IView
{
    string Text { set; }
}

public partial class View : System.Web.UI.UserControl, IView
{
    public Presenter Presenter { get; set; }

    public string Text
    {
        set
        {
            ltText.Text = value;
        }
    }
}

public class Presenter
{
    public Presenter(IView view)
    {
        view.Text = "Hello World";
    }
}

And the container configuration:

//Global.ascx.cs...
var builder = new ContainerBuilder();
builder.RegisterType<Simple.Core.Views.View>().As<Simple.Core.Views.IView>();
builder.RegisterType<Simple.Core.Views.Presenter>().AsSelf().InstancePerRequest();
_containerProvider = new ContainerProvider(builder.Build());
Daniel
  • 11
  • 1
  • 4
  • Found a solution over in [this thread](https://stackoverflow.com/questions/432425/using-autofac-with-asp-net-and-the-mvp-pattern) – Daniel Jun 24 '18 at 12:33

1 Answers1

0

Found a solution over in this thread.

public partial class View : System.Web.UI.UserControl, IView
{
    public Presenter.Factory PresenterFactory { get; set; }

    public string Text
    {
        set
        {
            lbText.Text = value;
        }
    }

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

public class Presenter
{
    public delegate Presenter Factory(IView view);

    public Presenter(IView view)
    {
        view.Text = "Hello World";
    }

}
Daniel
  • 11
  • 1
  • 4