Introduction
In this article, I will show you a simple implementation of Dependency Injection in the Web API. Here we create an application that implements Dependency Injection.
Step 1
Create a Web API application.
- Start Visual Studio 2012.
- From the start window Select "Installed" -> "Visual C#" -> "Web".
- Select "ASP.NET MVC4 Web Application" and click on the "Ok" button.

- From the "MVC4 Project" window select "Web API".

- Click on the "OK" button.
Step 2
Create Two Model classes first is "ResponseModel" and another as "ResultModel".
- In the "Solution Explorer".
- Right-click on the Model Folder.
- Select "Add" -> "Class".
- Select "Installed" -> "Visual C#" and select "Class".

Add the following code in the "ResponseModel.cs".
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace DepeninjecAPI.Models
- {
- public class ResponseModel
- {
- public int ID { get; set; }
- public DateTime Date { get; set; }
- }
- }
Add the following code in "ResultModel.cs" class.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace DepeninjecAPI.Models
- {
- public class ResultModel<T>
- {
- public int Full_count { get; set; }
- public int Pagecount { get; set; }
- public IEnumerable<T> Rslt { get; set; }
- }
- }
Step 3
Add a new Folder to the project.
- In the "Solution Explorer".
- Right-click on the Project.
- Select "Add" -> "New Folder"and change the name of it to "Collect".

Add a new interface in this folder.
- Right-click on the "Collect" folder.
- Select "Add" -> "New Items".
- Select "installed" -> "Visual C#" and select "Interface".

Add the following code in this interface:
- using DepeninjecAPI.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace DepeninjecAPI.Collect
- {
- public interface IRedingCollect
- {
- void Save(ResponseModel read);
- ResultModel<ResponseModel> Get();
- ResultModel<ResponseModel> Get(int No_page);
- }
- public class ReadingCollect :IRedingCollect
- {
- private readonly IList<ResponseModel> intercollect = new List<ResponseModel>();
- public const int PageSize = 5;
- public void Save(ResponseModel read)
- {
- intercollect.Add(new ResponseModel { ID = read.ID, Date = read.Date });
- }
- public ResultModel<ResponseModel> Get()
- {
- return this.Get(1);
- }
- public ResultModel<ResponseModel> Get(int No_page)
- {
- var Gap_No = (No_page - 1) * PageSize;
- return new ResultModel<ResponseModel>
- {
- Full_count = intercollect.Count(),
- Pagecount = No_page,
- Rslt = intercollect.Skip(Gap_No).Take(PageSize)
- };
- }
- }
- }



Join the conversation! Your thoughts help the community grow.