Create A Simple .NET Core 3.1 Web API In Repository Pattern

Introduction

 
This article is about Repository Pattern Architecture and is mainly focused on how to easily create the .NET Core Web API from the initial setup.
 

Repository Pattern

 
Repository pattern in C# is a way to implement data access by encapsulating the set of objects persisted in a data store and the operations performed over them,
providing a more object-oriented view of the persistence layer.
 
Some Advantages Of Using Repository Pattern
  • Code reusability will very high. 
  • Your business logic can be unit tested without data access logic.
  • Business entities are strongly typed with annotations.
  • Centralized data logic, business logic, and service logic.
Getting Started
 
Install the latest stable version of .NET CORE 3.1.5 from the official site of Microsoft by the below link
 
Link
 
https://dotnet.microsoft.com/download/dotnet-core/thank-you/sdk-3.1.301-windows-x64-installer
 
Next we will start creating the new project.  Follow the below steps 
 
In this project, we will have 4 sections:
  1. MyTestApp (.Net Core Application which contains controller,view,program.cs etc)
  2. MyTestApp.BAL (.Net Standard Library for business logic implementation)
  3. MyTestApp.DAL (.Net Standard Library for data access and other DB related implementation can be done)
  4. MyTestApp.IAL (.Net Standard Library for interface class implementation)
Note
We can have one more project to maintain all entities with access specifiers but in the below example I haven't created/included a separate project for that.
 
Step 1
 
Open Visual Studio and click on create a new project.
 
 
Step 2
 
Now select ASP.NET Core Web Application and click on "Next".
 
 
Step 3
 
Enter the project name, for example, I'm giving my project name as "MyTestApp" and click on "Create".
 
 
Step 4
 
Now select the .Net Core version in the next window and also select project type below. Select either project type as "API" or "Web Application (Model-View-Controller)", in this example, I'm going to select the version as "ASP.NET Core 3.1" and project type as "Web Application (Model-View-Controller)" and click on "Create".
 
 
Step 5
 
Once the project is created Left-click on the solution and in "Add" click on the "New Project".
 
 
Step 6
 
Add a new project of type "Class Library (.NET Standard)" and click on "Next".
 
 
Step 7
 
Select a project name as "ProjectName.BAL"(in my case MyTestApp.BAL) and click on "create"'.
 
 
Step 8
 
Repeat the above step for creating (adding) the following projects "ProjectName.DAL" and "ProjectName.IAL" 
 
Step 9
 
Left-click on "MyTestApp" and go to Build Dependencies and go to Project Dependencies. 
 
 
  • Select MyTestApp and select all projects in the "Depends on" section. 
  • Select MyTestApp.BAL and select "MyTestApp.DAL & MyTestApp.IAL" projects in the "Depends on" section. 

  • Select MyTestApp.IAL and select "MyTestApp.DAL" project in the "Depends on" section. 

 
Step 10
 
In "MyTestApp"Left-click on "Dependencies" and go to Add Reference. 
 
 
  • Select "MyTestApp.BAL, MyTestApp.DAL, MyTestApp.IAL" and click ok. 

  • Similarly Open MyTestApp.BAL andLeft-click on "Dependencies" and go to Add Reference. Select "MyTestApp.DAL, MyTestApp.IAL" and click ok.

  • Similarly Open MyTestApp.IAL andLeft-click on "Dependencies" and go to Add Reference. Select "MyTestApp.DAL" and click ok.
 

Basically, the above steps are followed to connect the project with one another and connect the build dependencies and to access the class or interface or entities or any custom classes can be accessed based on access specifiers.
 
Step 11
 
For better understanding,  I will be installing the swagger in the application to send the data to the controller from the user.
  • Open package manager console and run the following command: "Install-Package Swashbuckle.AspNetCore"
Step 12
 
Now Left-click on the controller and click on "Add" and click on "Controller" and then select "API Controller - Empty" and then give a name for your controller, in my case, I have given it as "MyNewAPIController".
 
 
And now create a custom class file with the following name "MyCustomEntity.cs" in "MyTestApp.DAL" and then create a class with the following variable where this variable is used in returning the value from API in the form of JSON response.
  1. using System;  
  2.   
  3. namespace MyTestApp.DAL  
  4. {  
  5.     public class MyCustomEntity  
  6.     {  
  7.         public class MyCustomResponse  
  8.         {  
  9.             public bool status { getset; }  
  10.             public string response { getset; }  
  11.         }  
  12.   
  13.     }  
  14. }  
 
And now create an interface file with the following name -  "IMyNewAPI.cs" in "MyTestApp.IAL" and then create an interface method for the sample API method.
  1. using System;  
  2. using static MyTestApp.DAL.MyCustomEntity;  
  3.   
  4. namespace MyTestApp.IAL  
  5. {  
  6.     public interface IMyNewAPI  
  7.     {  
  8.          MyCustomResponse GetAllData();  
  9.     }  
  10. }  
 
And now create a class file with the following name -  "MyNewApiBAL.cs" in "MyTestApp.BAL" and then implement the definition of the previously created interface.
  1. using MyTestApp.IAL;  
  2. using System;  
  3. using static MyTestApp.DAL.MyCustomEntity;  
  4.   
  5. namespace MyTestApp.BAL  
  6. {  
  7.     public class MyNewApiBAL : IMyNewAPI  
  8.     {  
  9.         public MyCustomResponse GetAllData()  
  10.         {  
  11.             MyCustomResponse response = new MyCustomResponse();  
  12.             try  
  13.             {  
  14.                 response.status = true;  
  15.                 response.response = "API called successfully";  
  16.             }  
  17.             catch (Exception ex)  
  18.             {  
  19.                 response.status = false;  
  20.                 response.response = "Exception occoured";  
  21.             }  
  22.             return response;  
  23.         }  
  24.     }  
  25. }  
 
And now replace the controller with the following code where it refers to the interface methods and also includes the route address and method headers eg.GET or POST.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Http;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. using MyTestApp.IAL;  
  8. using static MyTestApp.DAL.MyCustomEntity;  
  9.   
  10. namespace MyTestApp.Controllers  
  11. {  
  12.     [Route("MyNewAPI/")]  
  13.     [ApiController]  
  14.     public class MyNewAPIController : ControllerBase  
  15.     {  
  16.         private readonly IMyNewAPI _myNewAPI;  
  17.   
  18.         public MyNewAPIController(IMyNewAPI myNewAPI)  
  19.         {  
  20.             _myNewAPI = myNewAPI;  
  21.         }  
  22.   
  23.         [HttpGet]  
  24.         [Route("GetAllData")]  
  25.         [ProducesResponseType(StatusCodes.Status200OK)]  
  26.         [ProducesResponseType(StatusCodes.Status400BadRequest)]  
  27.         public async Task<IActionResult> GetAllData()  
  28.         {  
  29.             MyCustomResponse response = new MyCustomResponse();  
  30.             response = _myNewAPI.GetAllData();  
  31.             if (response.status == true)  
  32.             {  
  33.                 return Ok(response);  
  34.             }  
  35.             else  
  36.             {  
  37.                 return BadRequest(response);  
  38.             }  
  39.         }  
  40.     }  
  41. }  
 
Now we are all set for the final step. Last but not least, please do the one-time setup in the Startup.cs. The dependency injection takes place here on this page and contains the details about Swagger, all controllers, CROS, and services which we are going to use in our application.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Threading.Tasks;    
  5. using Microsoft.AspNetCore.Builder;    
  6. using Microsoft.AspNetCore.Hosting;    
  7. using Microsoft.Extensions.Configuration;    
  8. using Microsoft.Extensions.DependencyInjection;    
  9. using Microsoft.Extensions.Hosting;    
  10. using MyTestApp.BAL;    
  11. using MyTestApp.IAL;    
  12.     
  13. namespace MyTestApp    
  14. {    
  15.     public class Startup    
  16.     {    
  17.         public Startup(IConfiguration configuration)    
  18.         {    
  19.             Configuration = configuration;    
  20.         }    
  21.     
  22.         public IConfiguration Configuration { get; }    
  23.     
  24.         // This method gets called by the runtime. Use this method to add services to the container.    
  25.         public void ConfigureServices(IServiceCollection services)    
  26.         {    
  27.             services.AddControllersWithViews();    
  28.             services.AddControllers();    
  29.             services.AddMvc();    
  30.     
  31.             //swagger dependency    
  32.             services.AddSwaggerGen(c =>    
  33.             {    
  34.                 c.SwaggerDoc("v1"new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My New API", Version = "v1" });    
  35.             });    
  36.     
  37.             //configure DI for application services    
  38.             //every time you add a new controller with an interface implementation you need to register the same here    
  39.             services.AddTransient<IMyNewAPI, MyNewApiBAL>();    
  40.     
  41.             //Allow cros in API    
  42.             services.AddCors(options =>    
  43.             {    
  44.                 options.AddPolicy("AllowAllOrigins",    
  45.                     builder =>    
  46.                     {    
  47.                         builder.AllowAnyOrigin();    
  48.                         builder.AllowAnyHeader();    
  49.                         builder.AllowAnyMethod();    
  50.                     });    
  51.             });    
  52.         }    
  53.     
  54.     
  55.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.    
  56.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)    
  57.         {    
  58.             if (env.IsDevelopment())    
  59.             {    
  60.                 app.UseDeveloperExceptionPage();    
  61.             }    
  62.             else    
  63.             {    
  64.                 app.UseExceptionHandler("/Home/Error");    
  65.             }    
  66.             app.UseStaticFiles();    
  67.     
  68.             app.UseRouting();    
  69.     
  70.             app.UseAuthorization();    
  71.     
  72.             app.UseEndpoints(endpoints =>    
  73.             {    
  74.                 endpoints.MapControllerRoute(    
  75.                     name: "default",    
  76.                     pattern: "{controller=Home}/{action=Index}/{id?}");    
  77.             });    
  78.     
  79.             // Shows UseCors with CorsPolicyBuilder.    
  80.             app.UseCors("AllowAllOrigins");    
  81.     
  82.     
  83.             // Enable middleware to serve generated Swagger as a JSON endpoint.    
  84.             app.UseSwagger();    
  85.     
  86.             // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),     
  87.             // specifying the Swagger JSON endpoint.    
  88.             app.UseSwaggerUI(c =>    
  89.             {    
  90.                 c.SwaggerEndpoint("/swagger/v1/swagger.json""My API V1");    
  91.                 c.DefaultModelsExpandDepth(-1);    
  92.             });    
  93.     
  94.     
  95.             app.UseRouting();    
  96.         }    
  97.     }    
  98. }     
Step 13
 
Now run the application and sit back and rest for a while the application loads for you in your browser.
 
 
Step 14
 
Now put "/swagger" in front of "localhost:12567".i.e "localhost:12567/swagger" and press enter.
 
Step 15
 
And under MyNewAPI press on GetAllData API and press on Try it out and then press on Execute.
 
 
 

Conclusion

 
In this article, we discussed something interesting about how to easily create a .NET Core WEB API. In upcoming articles, we will discuss something more about .NET Core and Other services. Before saying goodbye to you I just want to let you know that this is my first article and a lot more interesting articles are coming up in the future. I hope you all enjoyed reading this.