Adding Dependency Injection to existing ASP.NET Web Forms

Dependency Injection can make code easier to maintain and test by removing code dependencies between classes and reduce overall cohesion in a system. It is possible and quite simple to setup Unity with WebForms so there is little reason not to benefit, first add a reference to Unity

PM> Install-Package Unity

Add a static class to register dependencies, this can be placed anywhere so long as it can be referenced by the web application code. If you follow the convention then it should be called UnityConfig and placed in the App_Start folder.

public class UnityConfig
{
    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<IMyInterface, MyInterfaceImplementation>();
    }
}

In the global.asax get the container using the extension and call the register types method created above 

protected void Application_Start(object sender, EventArgs e)
{
    IUnityContainer container = Application.GetContainer(); 
    UnityConfig.RegisterTypes(container);
}

Next unlike MVC, web forms do not have a constructor so dependencies need to be tagged with an attribute so the IoC container know what the dependencies are. Normally the dependency would be part of a controller constructor so this step would not be necessary, but with the web forms page life cycle we need to be explicit.

[Dependency]
public IMyInterface myDependency { get; set; }

Since there is not constructor the OnInit event is used to trigger the dependency resolution by calling the BuildUp method on the container.

protected override void OnInit(EventArgs e)
{
     HttpContext.Current.Application.GetContainer().BuildUp(this.GetType(), this);
     base.OnInit(e);
}

The same approach can be used for User Controls and Master Pages now when the page is requested the dependencies will be resolved by the OnInit event.