Dependency Injection on an ASP.NET Page

In order to have dependency injection on your ASP.NET pages, the best way to go is through a customized page handler factory. A page handler factory is a class directly or indirectly derived from PageHandlerFactory who has the responsibility to create a new instance of a Page. What we do is, we call the base class implementation of GetHandler method and then we call IUnityContainer's BuildUp method. Of course, we must also

  1. have previously initialized the Unity container, possibly on Application_Start method of Global.asax.cs
  2. configure interceptors for the types you want in Web.config. In this example, since I am registering an interface, I will be using InterfaceInterceptor, but you can also use VirtualMethodInterceptor or TransparentProxyInterceptor. I will talk about these in a future post.
  3. replace the existing page handler factory with our onw in Web.config

See the attached code, and replace ISomething for your own interface and ConcreteSomething, in Web.config, for the actual implementation of this interface.

                             

No Comments