How to use dependency injection in ASP.Net Web Forms

Dependency injection is a technique whereby one object (the dependency) is passed to another object that needs it. Dependency Injection is a realization of the inversion of control principle, which facilitates loose coupling and promotes testability and maintenance.
How To Use Dependency Injection In Asp Net Web Forms
How To Use Dependency Injection In Asp Net Web Forms

Dependency injection is a technique whereby one object (the dependency) is passed to another object that needs it. Dependency Injection is a realization of the inversion of control principle, which facilitates loose coupling and promotes testability and maintenance. The dependency injection principle states that the high-level modules in an application should not depend on the low-level modules. Rather, both should depend on abstractions.

Support for dependency injection was introduced in .Net Framework 4.7.2. This support enables you to leverage the benefits of dependency injection in ASP.Net Web Forms applications. This article provides a discussion of how we can work with dependency injection in ASP.Net Web Forms.


Create an ASP.Net Web Forms project

First off, let’s create an ASP.Net Core project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.Net Web Forms project in Visual Studio.

Launch the Visual Studio 2019 IDE.
Click on “Create new project.”
In the “Create new project” window, select “ASP.Net Web Application (.Net Framework)” from the list of templates displayed.
Ensure that the .Net Framework version is specified as “.Net Framework 4.7.2” in the drop-down control at the bottom of the screen.
Click Create.
In the “Create New ASP.Net Web Application” window shown next, select “Web Forms” as the project template. 
Ensure that the check boxes “Docker Support,” “MVC,” and “Web API” are unchecked as we won’t be using those features here.
Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either.
Click Create.

This will create a new ASP.Net Web Forms project in Visual Studio. We’ll use this project in the sections below to demonstrate how we can work with dependency injection in an ASP.Net Web Forms application.


Before you use dependency injection in ASP.Net Web Forms, you will need to make sure that your project targets .Net Framework 4.7.2 or later. If you have created your project in an earlier version of .Net Framework, you can retarget the project to .Net Framework 4.7.2. You can do this either by editing the project properties or by specifying the target framework in the web.config file as shown below.

<system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
...
</system.web>

The next step is to install the AspNet.WebFormsDependencyInjection.Unity NuGet package. Select the project you’ve created in the earlier section, then right-click and install AspNet.WebFormsDependencyInjection.Unity via the NuGet Package Manager. Accept any licensing agreements you might be prompted for during the installation. Alternatively, you can also install this package by entering the following command in the NuGet Package Manager Console.

Install-Package AspNet.WebFormsDependencyInjection.Unity


Create an entity class and interface in ASP.Net Web Forms

First let’s create the following entity class named Author.

public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
Next, we’ll create an interface called IAuthorRepository and insert the following code.

public interface IAuthorRepository
    {
        bool Create(Author author);
        Author Read(int id);
        List<Author> Read();
    }
The AuthorRepository class implements the IAuthorRepository interface as shown in the code snippet given below.

public class AuthorRepository : IAuthorRepository
    {
        public bool Create(Author author)
        {
            throw new System.NotImplementedException();
        }
        public Author Read(int id)
        {
            throw new System.NotImplementedException();
        }
        public List<Author> Read()
        {
            throw new System.NotImplementedException();
        }
    }


Create a container and register the types

Assuming you installed the necessary NuGet package in your project as described above, the next step is to create the Unity dependency injection container and register the types we would like to use. The following code can be used to create a Unity container.

var container = this.AddUnity();
You can use the Unity container to resolve dependencies on an object in the Application_Start event handler quite easily, as shown in the code snippet that follows.

container.RegisterType<IAuthorRepository, AuthorRepository>();
Note that you must include the following two namespaces in your application for the above code to work.

AspNet.WebFormsDependencyInjection.Unity
Unity

Here is the complete code of the Global class for your reference.

using Microsoft.AspNet.WebFormsDependencyInjection.Unity;
using System;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using Unity;

namespace WebformsDIDemo
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            var container = this.AddUnity();
            container.RegisterType<IAuthorRepository, AuthorRepository>();
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Use dependency injection in ASP.Net Web Forms

To leverage dependency injection in your Web Forms, you can use constructor injection as shown in the code snippet below.

public partial class _Default : Page
    {
      private IAuthorRepository _authorRepository;
        protected void Page_Load(object sender, EventArgs e)
        {
        }       
        public _Default(IAuthorRepository authorRepository)
        {
            _authorRepository = authorRepository;
        }
    }
Note the use of the argument constructor to pass the dependency at runtime.

With .Net Framework 4.7.2, dependency injection is available in ASP.Net Web Forms applications via Unity. The Unity Application Block is a lightweight dependency injection container. You can use dependency injection in ASP.Net pages, controls, handlers, modules, etc. Take advantage of dependency injection in ASP.Net Web Forms to simplify the creation of your objects, pass dependencies at runtime, and build flexible, loosely coupled applications.



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