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 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.
- 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:
- MyTestApp (.Net Core Application which contains controller,view,program.cs etc)
- MyTestApp.BAL (.Net Standard Library for business logic implementation)
- MyTestApp.DAL (.Net Standard Library for data access and other DB related implementation can be done)
- 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.
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using MyTestApp.IAL;
- using static MyTestApp.DAL.MyCustomEntity;
-
- namespace MyTestApp.Controllers
- {
- [Route("MyNewAPI/")]
- [ApiController]
- public class MyNewAPIController : ControllerBase
- {
- private readonly IMyNewAPI _myNewAPI;
-
- public MyNewAPIController(IMyNewAPI myNewAPI)
- {
- _myNewAPI = myNewAPI;
- }
-
- [HttpGet]
- [Route("GetAllData")]
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- public async Task<IActionResult> GetAllData()
- {
- MyCustomResponse response = new MyCustomResponse();
- response = _myNewAPI.GetAllData();
- if (response.status == true)
- {
- return Ok(response);
- }
- else
- {
- return BadRequest(response);
- }
- }
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using MyTestApp.BAL;
- using MyTestApp.IAL;
-
- namespace MyTestApp
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllersWithViews();
- services.AddControllers();
- services.AddMvc();
-
-
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My New API", Version = "v1" });
- });
-
-
-
- services.AddTransient<IMyNewAPI, MyNewApiBAL>();
-
-
- services.AddCors(options =>
- {
- options.AddPolicy("AllowAllOrigins",
- builder =>
- {
- builder.AllowAnyOrigin();
- builder.AllowAnyHeader();
- builder.AllowAnyMethod();
- });
- });
- }
-
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- else
- {
- app.UseExceptionHandler("/Home/Error");
- }
- app.UseStaticFiles();
-
- app.UseRouting();
-
- app.UseAuthorization();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllerRoute(
- name: "default",
- pattern: "{controller=Home}/{action=Index}/{id?}");
- });
-
-
- app.UseCors("AllowAllOrigins");
-
-
-
- app.UseSwagger();
-
-
-
- app.UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
- c.DefaultModelsExpandDepth(-1);
- });
-
-
- app.UseRouting();
- }
- }
- }
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.