Implementation of Castle Windsor DI container to ASP.NET WebForms 4.7.2. In previous versions there is no direct support due to mising extensibility point HttpRuntime.WebObjectActivator. You can find more details in news article.
Instalation to existing project
- Switch Target framework for your project to .NET Framework 4.7.2. If you don't have installed .NET Framework 4.7.2 developer pack. You can download it from here.
Check web.config and targetFramework in httpRuntime section. Both must be set to 4.7.2.
<system.web> <compilation debug="true" targetFramework="4.7.2"/> <httpRuntime targetFramework="4.7.2"/> </system.web>
- Add nuget package Havit.CastleWindsor.WebForms. Don't forget to reinstall other nuget packges, if you changed Target framework in previous step.
- Install nuget packge Castle.Windsor.
- Add this initiaizing code to Application_Start method in Global.asax. Extension method AddWindsorContainer will initialize new container and will use it for resolving dependencies.
IWindsorContainer container = this.AddWindsorContainer();
- Also add using to the header of global.asax
There are many areas you can use Dependency Injection in WebForms applications now. Here is a complete list:
- Pages and controls
- WebForms page
- User control
- Custom control
- IHttpHandler and IHttpHandlerFactory
- Health monitoring provider
- Any ProviderBase based provider created by System.Web.Configuration.ProvidersHelper.InstantiateProvider. e.g. custom sessionstate provider
Because it is not possible to use Dependency Injection through WebOjectActivator in Web Services (*.asmx), we added a workaround for this case, so you can do dependency injection to web services via properties.
How to inject to Web Services
- Web Service must inherit from the abstract class Havit.CastleWindsor.WebForms.InjectableWebServiceBase
- Every property, you want to inject must be marked with the attribute Havit.CastleWindsor.WebForms.InjectAttribute
- Every property, you want to inject must have a public getter and setter
We have prepared a simple example appliction with one page and one web service with Dependency Injection. See Havit.CastleWindsor.WebForms.Example appliction.
- If you hit the error, that a page (or an user control) cannot be created because of missing a contructor with zero arguments, check if you had switched your project to .NET FW 4.7.2 (don't forget to check compilation and httpRuntime elements in the web.config file).