How to integrate Dependency Injection in ASP.Net Web Forms

The Dependency Injection is one of my favorite concept which enhances code re-usability and makes more object oriented. Today, we will learn about injecting the Dependency in ASP.Net Web Forms using Unity Container.

Dependency Injection is a Software design pattern which we use in C# to reduce class dependency.

The Unity Container (Unity) is a lightweight, extensible dependency injection container. As we know, there are many dependency injection containers and unity is one of them.

Steps to implement DI (Dependency Injection) in project are as follows:-

Step 1 – Create a new ASP.Net Web Forms project

Open the Visual Studio and create a new ASP.Net Web Forms Empty project as follows-

Dependency Injection in ASP.Net Web Forms

 

Step 2 – Create few folders

Create few folders in root directory of project and make your project’s solution directory look like this-

Dependency Injection in ASP.Net Web Forms

 

Step 3 – Add a new Model class

Create an User.cs model in Model folder and paste below codes-

Dependency Injection in ASP.Net Web Forms

 

Step 4 – Add new interface

Add a new interface IUserRepository.cs  in IRepository  folder and paste below codes in that-

Dependency Injection in ASP.Net Web Forms

 

Step 5 – Add new repository class

Add a new repository UserRepository.cs  in Repository  folder and paste below codes in that-

Dependency Injection in ASP.Net Web Forms

 

Step 6 – Open Package Manager Console and install Unity.WebForms

Run below code in Package Manager Console in order to install the Unity Container-

Dependency Injection in ASP.Net Web Forms

Dependency Injection in ASP.Net Web Forms

 

It will add an ASP.Net folder in project and will add the Unity Container default class in that-

Dependency Injection in ASP.Net Web Forms

 

Step 7 – Register the Interface and Implementation classes

Register all your Interface and Implementation classes in UnityWebFormsStart.cs file.

Dependency Injection in ASP.Net Web Forms

 

Step 8 – Call the interface in your Default.aspx file

Dependency Injection in ASP.Net Web Forms

 

Step 9 – View the injected dependency

Now run the project and you would see that it has injected the required dependency while running the project-

Dependency Injection in ASP.Net Web Forms

 

Visit my Github Repository here to download the full project.

Follow this tutorial to Integrate Dependency Injection in ASP.Net MVC.

Thanks for reading 🙂

1 thought on “How to integrate Dependency Injection in ASP.Net Web Forms

Leave a Reply

Your email address will not be published. Required fields are marked *