Use Dependency Injection In WebForms Application

Dependency Injection design pattern is widely used in modern applications. It decouples objects to the extent that no client code needs to be changed simply because an object it depends changes to a different one.
Use Dependency Injection In Webforms Application
Use Dependency Injection In Webforms Application

Dependency Injection design pattern is widely used in modern applications.  It decouples objects to the extent that no client code needs to be changed simply because an object it depends changes to a different one. 

It brings you a lot of benefits, like reduced dependency, more reusable code, more testable code, etc.  in the past, it was very difficult to use Dependency Injection in WebForms application before.  Starting from .NET 4.7.2, it is now easy for developers to use Dependency Injection in WebForms applications.  With the UnityAdapter, you can add it to your existing WebForms application in 4 simple steps.


How to enable Dependency Injection in your existing WebForms application

Suppose you have a movie website which lists most popular movies in history.  You use repository pattern to separate the logic that retrieves the data and maps it to the business entity.  Currently you are creating business logic object and repository object in default.aspx page.  The code looks like bellow.

public partial class Default : System.Web.UI.Page
{
    private IPopularMovie movieMgr = new MovieManager(new XmlMovieRepository());

    public async Task<SelectResult> movieList_GetData()
    {
        var movies = await movieMgr.GetPopularMoviesAsync();
        return new SelectResult(movies.Count(), movies);
    }
}

Now simply follow 4 steps below, you will be able to adopt Dependency Injection to decouple the MovieManager from default.aspx page. The sample web application is on this Github repo.  And you can use tag to retrieve the code change in each step.

1. Retarget the project to .NET Framework 4.7.2. (Git Tag: step-1)

Open project property and change the targetFramework of the project to .NET Framework 4.7.2. You would also need to change targetFramework in httpRuntime section in web.config file as illustrated below.

2. Install AspNet.WebFormsDependencyInjection.Unity NuGet package. (Git Tag: step-2)

3. Register types in Global.asax. (Git Tag: step-3)

using System;
using Microsoft.AspNet.WebFormsDependencyInjection.Unity;
using PopularMovies.Bizlogic;
using PopularMovies.Repository;
using Unity;

namespace PopularMovies
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            var container = this.AddUnity();

            container.RegisterType<IPopularMovie, MovieManager>();
            container.RegisterType<IMovieRepository, XmlMovieRepository>();
        }
    }
}

4. Refactor Default.aspx.cs. (Git Tag: step-4)

public partial class Default : System.Web.UI.Page
{
    private IPopularMovie movieMgr;
    public Default(IPopularMovie movieManager)
    {
        movieMgr = movieManager;
    }

    public async Task<SelectResult> movieList_GetData()
    {
        var movies = await movieMgr.GetPopularMoviesAsync();
        return new SelectResult(movies.Count(), movies);
    }
}


Areas that Dependency Injection can be used

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
IHttpModule

Providers

BuildProvider
ResourceProviderFactory
Health monitoring provider

Any ProviderBase based provider created by System.Web.Configuration.ProvidersHelper.InstantiateProvider. e.g. custom sessionstate provider
 

Summary

Using Microsoft.AspNet.WebFormsDependencyInjection.Unity NuGet package on .net framework 4.7.2, Dependency Injection can be easily added into your existing WebForms application. 


Are you looking to create valuable SEO content at an affordable price? Our SEO platform allows you to be creative, while still helping you boost your SEO ranking. Sign up today to find out more.

Leave a message

Full Name
Email
Mobile
Description