.Net Core WebAPI, Repository Pattern, Generics, Swagger And More

Introduction

 
This is my first blog for this site, I hope you enjoy it. Please make a comment if you want to tell me something I could improve.
 
Here I will show you a simple way to implement a repository pattern from scratch to manage the Data Access from  WEB API in Net Core 3.
 
I will include: 
  • N-Layer Architecture
  • Web Api
  • EntityCore
  • Generics
  • DI
  • Repository Pattern
  • Swagger
Prerequisites to start:
  • NetCore SDK 3
  • Knowledge of the structure of a webapi (folders and files)
  • SqlServer
  • VisualStudio Code
  • Knowledge of Generics
  • Knowledge of DI
Let's go through it step by step.
 
STEP 1 - Creating the Global Arquitecture of the application
 
Open the Visual Studio code inside the folder you want to make your project.
 
Open a new Console Terminal and create a new WebApi with the following command,
  1. dotnet new webapi -o RP.Api     
RP.Api is the name of my WebApiLayer
 
Then we will create the other class libraries to make the rest of the layers with the following commands,
  1. dotnet new classlib -o RP.Core    
  2. dotnet new classlib -o RP.BL      
  3. dotnet new classlib -o RP.DAL  
The project structure is created as we can see below:
 
STEP 2 - Creating some models to persist
 
Inside the RP.Core layer, create a new folder named Models and two classes to make this example Category and Product:
  1. using System.ComponentModel.DataAnnotations;         
  2.         
  3. namespace RP.Core.Models         
  4. {         
  5.     public class Category         
  6.     {         
  7.         [Key]         
  8.         public int Id { getset; }         
  9.         public string Name { getset; }         
  10.         public string Description { getset; }         
  11.     }         
  12. }   
  1. using System.ComponentModel.DataAnnotations;         
  2.         
  3. namespace RP.Core.Models         
  4. {         
  5.     public class Product         
  6.     {         
  7.         [Key]         
  8.         public int Id { getset; }         
  9.         public string Name { getset; }         
  10.         public string Description { getset; }         
  11.         public decimal Price { getset; }         
  12.         public int CategoryId { getset; }         
  13.         public Category Category{get;set;}         
  14.     }         
  15. }  
If you get some errors with DataAnnotations, run:
  1. dotnet add package System.ComponentModel.Annotations       
The database will be created automatically, don't worry about it.
 
STEP 3 - Create the Repositories
 
Inside the RP.DAL layer we will create the following folder structure
 
 
Then add the package of EntityCore to manage the persistence. In order to do that run the following command in the Terminal Console,
  1. dotnet add package Microsoft.EntityFrameworkCore.SqlServer       
Inside the Infrastructure folder, create a class named AppDbContext that will manage the context from EF Core, and it creates data related to Categories (because I only show the CRUD of Products),
  1. using Microsoft.EntityFrameworkCore;       
  2. using RP.Core.Models;       
  3.       
  4. namespace RP.DAL.Infrastructure       
  5. {       
  6.     public class AppDbContext: DbContext       
  7.     {       
  8.         public AppDbContext(DbContextOptions<AppDbContext> options)       
  9.             :base(options)       
  10.         {       
  11.         }       
  12.         public DbSet<Product> Products{ getset; }       
  13.         public DbSet<Category> Categories { getset; }       
  14.         protected override void OnModelCreating(ModelBuilder modelBuilder)       
  15.         {       
  16.             modelBuilder.Entity<Category>().HasData(       
  17.                 new Category()       
  18.                 {       
  19.                     Id = 1,       
  20.                     Name = "Electronics",       
  21.                     Description = "Electronic Items"       
  22.                 },       
  23.                 new Category()       
  24.                 {       
  25.                     Id = 2,       
  26.                     Name = "Clothes",       
  27.                     Description = "Dresses"       
  28.                 },       
  29.                 new Category()       
  30.                 {       
  31.                     Id = 3,       
  32.                     Name = "Grocery",       
  33.                     Description = "Grocery Items"       
  34.                 });       
  35.         }       
  36.      }       
  37. }     
If you get an error in Product and Category, remember to add the reference from RP.DAL toRP.Core classLib.
Inside the IRepositories folder we will create the interface of the generic repository base to manage the simple CRUD of every repository. So, create an interface called IBaseRepository.cs as we can see:
  1. using System;       
  2. using System.Collections.Generic;       
  3. using System.Linq.Expressions;       
  4.       
  5. namespace RP.DAL.IRepositories       
  6. {       
  7.     public interface IBaseRepository<T> where T : class       
  8.     {       
  9.         void Add(T entity);       
  10.         void Update(T entity);       
  11.         void Delete(T entity);       
  12.         IEnumerable<T> GetAll(params Expression<Func<T, object>[] includes );       
  13.         IEnumerable<T> Filter(Expression<Func<T, bool>> where, params Expression<Func<T, object>>[] includes);       
  14.         int SaveChanges();       
  15.     }  
The last thing we have to do to finish our Repository Layer is create a generic base class that implements all the methods of the Base interface.
 
So inside the Repositories folder, create a new class called BaseRepository.cs,
  1. using System;       
  2. using System.Collections.Generic;       
  3. using System.Linq;       
  4. using System.Linq.Expressions;       
  5. using Microsoft.EntityFrameworkCore;       
  6. using RP.DAL.Infrastructure;       
  7. using RP.DAL.IRepositories;       
  8.        
  9.  namespace Base.Dal.Repositories       
  10. {       
  11.     public class BaseRepository<T> : IBaseRepository<T> where T : class       
  12.     {       
  13.         internal AppDbContext _context;       
  14.         public BaseRepository(AppDbContext context)       
  15.         {       
  16.             this._context = context;       
  17.         }       
  18.         public virtual void Add(T entity) => _context.Set<T>().Add(entity);       
  19.             
  20.         public virtual void Update(T entity) => _context.Entry(entity).State = EntityState.Modified;       
  21.             
  22.         public virtual void Delete(T entity) => _context.Remove(entity);       
  23.             
  24.         public IEnumerable<T> GetAll(params Expression<Func<T, object>>[] includes)       
  25.         {       
  26.             var query = _context.Set<T>().AsQueryable();       
  27.             foreach (Expression<Func<T, object>> i in includes)       
  28.             {       
  29.                 query = query.Include(i);       
  30.             }       
  31.             return query.ToList();       
  32.         }       
  33.             
  34.         public IEnumerable<T> Filter(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes)       
  35.         {       
  36.             var query = _context.Set<T>().Where(predicate);       
  37.             foreach (Expression<Func<T, object>> i in includes)       
  38.             {       
  39.                 query = query.Include(i);       
  40.             }       
  41.             return query.ToList();       
  42.          }       
  43.          public int SaveChanges() => _context.SaveChanges();       
  44.     }       
  45. }    
This class manages the CRUD operations of every type passed as generic. This class allows me to call a GetAll (the “includes” parameter represents all the lazy loading you want to load),  find by the specific filter, create, update or delete.
 
STEP 4 - Create the Services inside the Bussiness Layer
 
Inside the RP.BL layer we will create the following folder structure:
 
 
There are so many models that don't have buissness logic. In order not to create a Service class for those, with the great help of generics, we can define only one Base service to manage the way to the repository and persist the data. So the interface Base Service is,
  1. using System;       
  2. using System.Collections.Generic;       
  3. using System.Linq.Expressions;       
  4.       
  5. namespace RP.BL.IServices       
  6. {       
  7.     public interface IBaseService<T> where T : class       
  8.     {       
  9.          IEnumerable<T> Get(Expression<Func<T, bool>> where = null,params Expression<Func<T, object>>[] includes);       
  10.          IEnumerable<T> GetAll(params Expression<Func<T, object>>[] includes);       
  11.          int Create(T t);       
  12.          int Update(T t);       
  13.          void Delete(T t);       
  14.     }       
  15. }    
And the Base Service that implements the interface is the following,
  1. using System;       
  2. using System.Collections.Generic;       
  3. using System.Linq.Expressions;       
  4. using RP.BL.IServices;       
  5. using RP.DAL.IRepositories;       
  6.       
  7. namespace RP.BL.Services       
  8. {       
  9.     public class BaseService<T> : IBaseService<T> where T : class       
  10.     {       
  11.         public readonly IBaseRepository<T> _TRepository;       
  12.         public BaseService(IBaseRepository<T> TRepository)       
  13.         {       
  14.             this._TRepository = TRepository;       
  15.         }       
  16.       
  17.         public int Create(T T)       
  18.         {       
  19.             _TRepository.Add(T);       
  20.             int result = _TRepository.SaveChanges();       
  21.             return result;       
  22.         }       
  23.       
  24.         public int Update(T T)       
  25.         {       
  26.             _TRepository.Update(T);       
  27.             int result = _TRepository.SaveChanges();       
  28.             return result;       
  29.         }       
  30.       
  31.         public void Delete(T T)       
  32.         {       
  33.             _TRepository.Delete(T);       
  34.             _TRepository.SaveChanges();       
  35.         }       
  36.       
  37.         public IEnumerable<T> Get(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes)       
  38.         {       
  39.             return _TRepository.Filter(predicate, includes);       
  40.         }       
  41.       
  42.         public IEnumerable<T> GetAll(params Expression<Func<T, object>>[] includes)       
  43.         {       
  44.             return _TRepository.GetAll(includes);       
  45.         }       
  46.     }       
  47. }       
And we finished the Business Layer (remember that if you have a model with its own business logic, you have to create an interface service, and a service implementation for that model).
 
STEP 5 - Making our Web Api
 
First of all, move your terminal inside the RP.Api and add the dependency to EF Core with the command:
  1. dotnet add package Microsoft.EntityFrameworkCore.SqlServer     
Add the dependency to the other class libraries (RP. Core, RP. DAL and RP.BL)
 
Let's install swagger with the following command:
  1. dotnet add RP.Api.csproj package Swashbuckle.AspNetCore -v 5.0.0   
Let's open the Startup.cs and check that your ConfigureServices method is the same as mine:
  1. public void ConfigureServices(IServiceCollection services)       
  2.         {       
  3.             services.AddControllers();       
  4.             services.AddDbContext<AppDbContext>(o => o.UseSqlServer(Configuration.GetConnectionString("ProductDB")));       
  5.             services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));       
  6.             services.AddScoped(typeof(IBaseService<>), typeof(BaseService<>));       
  7.             services.AddSwaggerGen(c =>       
  8.             {       
  9.                 c.SwaggerDoc("v1"new OpenApiInfo { Title = "My API", Version = "v1" });       
  10.             });       
  11.         }    
The “services.AddDbContext” line adds the context related to our connection string defined in the appsettings.json.
 
The “services.AddScoped” is necesary to manage our Dependency Injection inside the controllers and services.
 
The “services.AddSwaggerGen” is necesary to use swagger and test our application.
 
Now check the method below called public void Configure,
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)       
  2.         {       
  3.             //creating db schema       
  4.             using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())       
  5.             {       
  6.                     var context = serviceScope.ServiceProvider.GetRequiredService<AppDbContext>();       
  7.                     context.Database.EnsureCreated();       
  8.             }       
  9.             if (env.IsDevelopment())       
  10.             {       
  11.                 app.UseDeveloperExceptionPage();       
  12.             }       
  13.             app.UseHttpsRedirection();       
  14.             app.UseRouting();       
  15.             app.UseAuthorization();       
  16.             app.UseEndpoints(endpoints =>       
  17.             {       
  18.                 endpoints.MapControllers();       
  19.             });       
  20.             // Enable middleware to serve generated Swagger as a JSON endpoint.       
  21.             app.UseSwagger();       
  22.             // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),       
  23.             // specifying the Swagger JSON endpoint.       
  24.             app.UseSwaggerUI(c =>       
  25.             {       
  26.                 c.SwaggerEndpoint("/swagger/v1/swagger.json""My API V1");       
  27.                  c.RoutePrefix = string.Empty;       
  28.             });       
  29.         }   
The first line is necesary to create the database and the schema (you are welcome).
 
And the other lines I added are related to make swagger work (app.UseSwagger and app.UseSwaggerUI).
 
The last thing we have to do is create inside the Controllers folder the controller that will expose the endpoints of our product, ProductsController.cs,
  1. using System;       
  2. using System.Collections.Generic;       
  3. using System.Linq;       
  4. using Microsoft.AspNetCore.Mvc;       
  5. using RP.BL.IServices;       
  6. using RP.Core.Models;       
  7.       
  8. namespace RP.Api.Controllers       
  9. {       
  10.     [ApiController]       
  11.     [Route("api/[controller]")]       
  12.     public class ProductsController : ControllerBase       
  13.     {       
  14.         private readonly IBaseService<Product> _productService;       
  15.         public ProductsController(IBaseService<Product> _productService)       
  16.         {       
  17.             this._productService = _productService;       
  18.         }       
  19.       
  20.         [HttpGet]       
  21.         public IActionResult Get()       
  22.         {       
  23.             var products = _productService.GetAll();       
  24.             return new OkObjectResult(products);       
  25.         }       
  26.       
  27.         [HttpGet,Route("{Id}")]       
  28.         public IActionResult Get(int Id)       
  29.         {       
  30.             //we want to find the product by id and load the category        
  31.             var products = _productService.Get(x=> x.Id == Id, i=>i.Category);       
  32.             if(!products.Any()){       
  33.                 return new NoContentResult();       
  34.             }       
  35.             return new OkObjectResult(products.First());       
  36.         }       
  37.       
  38.         [HttpPost]       
  39.         public IActionResult Post([FromBody] Product product)       
  40.         {       
  41.             _productService.Create(product);       
  42.             return CreatedAtAction(nameof(Get), new { id = product.Id }, product);       
  43.         }       
  44.       
  45.         // PUT: api/Product/5       
  46.         [HttpPut("{id}")]       
  47.         public IActionResult Put(int id,[FromBody] Product product)       
  48.         {       
  49.             if(product!= null){       
  50.                 _productService.Update(product);       
  51.                 return new OkResult();       
  52.             }       
  53.             return new NoContentResult();       
  54.         }       
  55.       
  56.         [HttpDelete("{id}")]       
  57.         public IActionResult Delete(int id)       
  58.         {       
  59.             var products = _productService.Get(x=> x.Id == id);       
  60.             if(!products.Any()){       
  61.                 return new NoContentResult();       
  62.             }       
  63.             _productService.Delete(products.First());       
  64.             return new OkResult();       
  65.         }       
  66.     }       
  67. }   
Now our API is finally ready to be tested. Press F5 and test it with swagger (Remember to have defined the connection string inside the appsettings.json).
 
 
The Endpoint /api/Products get all the products stored without loading the category object.
 
The Endpoint /api/Products/{id} Load the specific product with the category object where you can see that our lazy loading works well.
 

Summary

 
The repository pattern has been implemented, with generics, DI, Swagger and more. Sorry for not making a long explanation of every concept because then the  blog would be longer.
 
It is easy to implement and not too hard to understand. Please feel free to comment and give me your opinions about this pattern and my implementation.