1

I was wondering how to wire up Castle Windsor in WebForms.

I'm assuming that the second line wires up the controllers in MVC:

// Initialize Windsor
IWindsorContainer container = new WindsorContainer().Install(FromAssembly.This());
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container.Kernel));

How do I then wire up WebForms in ASP.NET?

I had a project which I have modified into an identical WebForms setup. Everything works up until the point where I want Castle Windsor to inject ISession into the ASPX page. It simply doesn't and I am under the assumption that the second line of code, above, is what does it for MVC controllers.

I have this in my nHibernate installer, in teh same place on both projects:

container.Register(Component.For<ISession>()
            .LifeStyle.PerWebRequest
            .UsingFactoryMethod(kernel => kernel.Resolve<ISessionFactory>().OpenSession()));

I had originally assumed this would do it but it is not the case.

I have been stuck on this for days and with very little official documentation on this I am close to ripping my hair out, what's left of it.

I do know the ASP.NET WebForms are not specifically designed to work with dependancy injection but Ninject have done it, albeit with a little hacking, if I can confirm that Castle Windsor is not compatible and/or will no longer support WebForms I will move to something else.

Anthony
  • 441
  • 1
  • 5
  • 20

1 Answers1

0

I managed to stuff Castle Windsor in to WebForms using the code here How to use Castle Windsor with ASP.Net web forms? It uses an an attribute to mark where a dependency should be injected in the a WebFrom.

I then used an MVP pattern. Each WebForm had a presenter

public partial class TestPage : UserControl, IShowTestPage
{
    [Inject]
    public TestPagePresenter Presenter { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack) return;

        this.Presenter.OnViewInitialized();
    }

    public string TestMessage
    {
        get { return litTestMessage.Text; }
        set { litTestMessage.Text = value; }
    }
}

As the Presenter is resolved form the container, it is then back to normal for wiring up the dependencies

public interface IShowTestPage {
    string TestMessage { get; set;}
}

public class TestPagePresenter {
    private ISession session;

    public TestPagePresenter(ISession session) {
        this.session = session;
    }

    private IShowTestPage view;
    public IShowTestPage { set { view = value; } }  

    public void OnViewInitialized {
        TestMessage = session.Query("some database query");
    }

}

My solution was based on a great article by Billy McCafferty

Community
  • 1
  • 1
Keith Bloom
  • 2,391
  • 3
  • 18
  • 30
  • Thanks, just what I was looking for. Although I've gone back to basics and ripped out Castle. If I ever need it again I know where to look. – Anthony Aug 11 '11 at 21:45