BaseApiController

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.

Those who are already familiar with the C# class inheritance mechanism will definitely know the purpose of a Base class and how to use it. In the unlikely case that you aren't, just think of it as a parent class that can be created to allow a number of other derived classes to inherit all the members, properties, and behaviors defined there. This pattern is extremely popular in object-oriented programming, although the semantics may vary from language to language; for example, in Java, a Base class is called Superclass, while the derived classes are known as Subclasses.

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
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.213.238