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.