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-
Step 2 – Create few folders
Create few folders in root directory of project and make your project’s solution directory look like this-
Step 3 – Add a new Model class
Create an User.cs
model in Model
folder and paste below codes-
public class User { public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
Step 4 – Add new interface
Add a new interface IUserRepository.cs
in IRepository
folder and paste below codes in that-
public interface IUserRepository { IEnumerable<User> GetUsers(); }
Step 5 – Add new repository class
Add a new repository UserRepository.cs
in Repository
folder and paste below codes in that-
public class UserRepository : IUserRepository { IList<User> userList = new List<User>(); public UserRepository() { User user = new User { Email = "jimcute8879@gmail.com", FirstName = "Jameer", LastName = "Khan" }; userList.Add(user); } public IEnumerable<Model.User> GetUsers() { return userList; } }
Step 6 – Open Package Manager Console and install Unity.WebForms
Run below code in Package Manager Console in order to install the Unity Container-
Install-Package Unity.WebForms
It will add an ASP.Net folder in project and will add the Unity Container default class in that-
Step 7 – Register the Interface and Implementation classes
Register all your Interface and Implementation classes in UnityWebFormsStart.cs
file.
private static void RegisterDependencies(IUnityContainer container) { // TODO: Add any dependencies needed here container.RegisterType<IUserRepository, UserRepository>(); }
Step 8 – Call the interface in your Default.aspx file
[Dependency] public IUserRepository _userRepository { get; set; } protected void Page_Load(object sender, EventArgs e) { var users = _userRepository.GetUsers(); }
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-
Visit my Github Repository here to download the full project.
Follow this tutorial to Integrate Dependency Injection in ASP.Net MVC.
Thanks for reading 🙂