Member-only story

Dynamic Reference Data in ASP.NET Core APIs: A Generic Approach

Sunny Sun
3 min readOct 12, 2024

--

Reference data can provide consistent and standardized information throughout a system. A straightforward approach to handling reference data is to use a switch case within a reference data service. However, as the number of reference data types increases, this approach can become increasingly cumbersome and difficult to maintain.

In my previous post, I walk through how to handle reference data in NestJS. In this article, we’ll explore how to implement dynamic reference data endpoints in ASP.NET Core APIs using C#. We’ll move away from a monolithic switch-case approach and embrace a generic pattern that adapts to various reference data types.

Using Switch Case

We can use the switch case to handle a small and relatively static set of reference data types. Below is an example.

public class ReferenceDataService
{
public async Task<IEnumerable<RefData>> GetRefDataByTypeAsync(string type)
{
switch (type)
{
case "countries":
return await _countryRepository.GetAllAsync();
case "productCategories":
return await _productCategoryRepository.GetAllAsync();
// ... other cases
default:
throw new ArgumentException("Invalid reference data type");
}
}
}

However, using a switch case isn’t an ideal solution. The Challenges of the Switch-Case Approach are:

  • Code Rigidity: Adding new reference data types requires modifying the switch statement, making maintenance difficult.
  • Limited Reusability: Code becomes specific to the handled data types, hindering reusability.

Generic Strategy Pattern with keyedServiceProvider

A better approach is using the generic strategy pattern for retrieving reference data. First, let’s define our reference data service.

Interface and Reference data service

public interface IReferenceDataService
{
Task<IEnumerable<RefData>> GetRefDataByType(string refDataType);
}


public class ReferenceDataService : IReferenceDataService
{
private readonly IServiceProvider…

--

--

Sunny Sun
Sunny Sun

Written by Sunny Sun

I am full stack developer. Love coding, learning, writing. Checkout my NestJS course: https://shorturl.at/cpJM7, visit my blog https://coffeethinkcode.com

No responses yet

Write a response