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")…

--

--

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