I have started writing tips on my different blog instead of this one. Make sure to follow that one so that you can get latest updates. Here is the link- StackBlogger: Tips and Tricks about Programming
Also follow my another Blog where I write how to make money online, tips about blogging, content creation etc. Here is the link- FlexiPlanet: A hub for Content Marketing.
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
inIRepository
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
inRepository
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.That’s all!!!
Any comment regarding DI are most welcome..