I am in the process of introducing a Dependency Injection framework into an existing WebForms application (using Castle Windsor).
I have pretty deep experience with DI, and tend to very strongly favor constructor injection over setter injection. If you are familiar with Webforms, you know that the ASP.Net framework handles the construction of page and control objects, making true constructor injection impossible.
My current solution is to register the container in the Application_Start event of the Global.asax, and keep the container as a public static variable in Global as well. I then simply resolve each service that I need directly in the page or control when I need them. So at the top of each page, I end up with code like this:
private readonly IMyService _exposureManager = Global.IoC.Resolve<IMyService>();
private readonly IMyOtherService _tenCustomersExposureManager = Global.IoC.Resolve<IMyOtherService>();
Obviously, I don't like having all these references to the container scattered about my application or having my page/control dependencies be non-explicit, but I have not been able to find a better way.
Is there a more elegant solution for using DI with Webforms?
PageHandlerFactory
, in the case of WebForms). It seems to say that because of code-behind class limitations, you will have to use setter injection. It also, interestingly, shows how Microsoft Managed Extensibility Framework (MEF) can help you to solve this and similar DI problems in a very useful and slightly non-standard way. – MikeBeaton