Our .NET Web API controllers get their job done; however, they're all affected by a noticeable flaw--the amount of duplicate code we used to make them all behave in the same way, although with different entities. More specifically, this means the following:
- They all have a DbContext property and a constructor that retrieves it through dependency injection
- They all create a number of JsonSerializerSettings objects configured in the same way
This is a rather common issue when working with the MVC pattern, where the same interfaces and approaches are often adopted multiple times and within different controllers.
Luckily enough, repeating a behavior doesn't necessarily mean repeating the code; we can easily cut these dupes with the help of a Base class.
Let's try to put together a Base class for our web API controllers that will take care of the repeating tasks summarized earlier. From Solution Explorer, right-click on the /Controllers/ folder and add a new BaseApiClontroller.cs class file with the following code:
using System;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using TestMakerFreeWebApp.Data;
using Mapster;
namespace TestMakerFreeWebApp.Controllers
{
[Route("api/[controller]")]
public class BaseApiController : Controller
{
#region Constructor
public BaseApiController(ApplicationDbContext context)
{
// Instantiate the ApplicationDbContext through DI
DbContext = context;
// Instantiate a single JsonSerializerSettings object
// that can be reused multiple times.
JsonSettings = new JsonSerializerSettings()
{
Formatting = Formatting.Indented
};
}
#endregion
#region Shared Properties
protected ApplicationDbContext DbContext { get; private set; }
protected JsonSerializerSettings JsonSettings { get; private
set; }
#endregion
}
}