Skip to main content

Repository with Factory Pattern in .NET Core using an Item API

 

Imagine you're building an Item API where you need to manage different data sources—SQL Server for some operations and Cosmos DB for others. But you don't want to hard-code the data access logic directly into your API because you want the flexibility to switch databases in the future or even to use multiple databases simultaneously. This is where a combination of the Repository and Factory patterns comes to the rescue!

In this blog, we’ll break down how to implement these patterns together to decouple your data access logic from your API, making it scalable, maintainable, and easily testable. Let’s dive in!

1. The Challenge: Why Combine Repository and Factory?

In an API like the Item API, you might face a situation where you have multiple data stores for different types of items. For example:

  • Some items are stored in SQL Server.
  • Others are stored in Cosmos DB.

If you hard-code the logic for data storage within your API, it becomes tightly coupled to a specific database, making it difficult to scale or switch databases.

The solution? Combine the Repository pattern to abstract data access and the Factory pattern to choose the appropriate data source at runtime.

2. What Are Repository and Factory Patterns?

Before we get into the code, let’s quickly break down the two patterns we’re using:

  • Repository Pattern: This pattern creates a layer between the data access logic and the business logic of an application. It abstracts the way you access data, allowing you to switch between different data sources without changing your business logic.

  • Factory Pattern: This pattern is responsible for creating objects without specifying the exact class of the object that will be created. It provides flexibility by deciding at runtime which implementation to use.

When we combine these two, we get a flexible, decoupled system where the repository can be chosen dynamically based on a factory, depending on which data store is needed.

3. Step-by-Step Implementation of the Repository with Factory Pattern

Let’s walk through the implementation step by step using the Item API.

Step 1: Define the Item Entity

We need to create a simple Item class that represents the objects stored in the databases.

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public double Price { get; set; }
}

Step 2: Create the IRepository Interface

The IRepository interface defines the common operations for handling items, regardless of the underlying database.

public interface IRepository<T>
{
    IEnumerable<T> GetAll();
    T GetById(int id);
    void Add(T entity);
    void Update(T entity);
    void Delete(int id);
}

Step 3: Implement SQL and Cosmos Repositories

Now, we’ll create two repository classes: one for SQL and one for Cosmos DB.

SQL Repository Implementation:

public class SqlItemRepository : IRepository<Item>
{
    private readonly DbContext _context;

    public SqlItemRepository(DbContext context)
    {
        _context = context;
    }

    public IEnumerable<Item> GetAll() => _context.Set<Item>().ToList();

    public Item GetById(int id) => _context.Set<Item>().Find(id);

    public void Add(Item entity)
    {
        _context.Set<Item>().Add(entity);
        _context.SaveChanges();
    }

    public void Update(Item entity)
    {
        _context.Set<Item>().Update(entity);
        _context.SaveChanges();
    }

    public void Delete(int id)
    {
        var item = _context.Set<Item>().Find(id);
        if (item != null)
        {
            _context.Set<Item>().Remove(item);
            _context.SaveChanges();
        }
    }
}
Cosmos DB Repository Implementation:
public class CosmosItemRepository : IRepository<Item>
{
    private readonly CosmosDbContext _context;

    public CosmosItemRepository(CosmosDbContext context)
    {
        _context = context;
    }

    public IEnumerable<Item> GetAll() => _context.Items.ToList();

    public Item GetById(int id) => _context.Items.FirstOrDefault(i => i.Id == id);

    public void Add(Item entity)
    {
        _context.Items.Add(entity);
        _context.SaveChanges();
    }

    public void Update(Item entity)
    {
        _context.Items.Update(entity);
        _context.SaveChanges();
    }

    public void Delete(int id)
    {
        var item = _context.Items.FirstOrDefault(i => i.Id == id);
        if (item != null)
        {
            _context.Items.Remove(item);
            _context.SaveChanges();
        }
    }
}

Step 4: Create the Repository Factory

The RepositoryFactory will decide at runtime whether to use the SQL or Cosmos DB repository based on some configuration or logic.

public class RepositoryFactory
{
    private readonly DbContext _sqlContext;
    private readonly CosmosDbContext _cosmosContext;

    public RepositoryFactory(DbContext sqlContext, CosmosDbContext cosmosContext)
    {
        _sqlContext = sqlContext;
        _cosmosContext = cosmosContext;
    }

    public IRepository<Item> CreateRepository(string repositoryType)
    {
        return repositoryType switch
        {
            "SQL" => new SqlItemRepository(_sqlContext),
            "Cosmos" => new CosmosItemRepository(_cosmosContext),
            _ => throw new ArgumentException("Invalid repository type"),
        };
    }
}

Step 5: Use the Factory in the Controller

Finally, we’ll inject the RepositoryFactory into the ItemController and use it to access the appropriate repository.

[ApiController]
[Route("api/[controller]")]
public class ItemController : ControllerBase
{
    private readonly RepositoryFactory _repositoryFactory;

    public ItemController(RepositoryFactory repositoryFactory)
    {
        _repositoryFactory = repositoryFactory;
    }

    [HttpGet]
    public IActionResult GetItems([FromQuery] string repoType)
    {
        var repository = _repositoryFactory.CreateRepository(repoType);
        var items = repository.GetAll();
        return Ok(items);
    }

    [HttpPost]
    public IActionResult CreateItem([FromQuery] string repoType, [FromBody] Item item)
    {
        var repository = _repositoryFactory.CreateRepository(repoType);
        repository.Add(item);
        return Ok();
    }

    // You can implement the other CRUD methods similarly.
}

4. Testing the Implementation

Now, you can test this API by passing a query parameter to specify the data store. For example:

  • To use SQL:
    GET /api/item?repoType=SQL

  • To use Cosmos DB:
    GET /api/item?repoType=Cosmos

With this approach, you have a highly flexible system that allows you to switch between different data sources with minimal code changes. You’ve effectively separated the data access logic from the API, ensuring that future enhancements like adding a new database type won’t disrupt the existing code.

5. Advantages of Combining Repository with Factory

  • Separation of Concerns: The API is no longer concerned with how data is stored, only that it can access it.
  • Scalability: Easily add new data sources (e.g., MongoDB or Redis) by simply creating new repositories.
  • Testability: By injecting dependencies and abstracting data access, it becomes easier to mock repositories in unit tests.
  • Flexibility: Dynamic runtime decision-making allows different parts of the application to use different repositories without changing the API logic.

6. Conclusion: A Flexible, Scalable, and Clean Approach

By combining the Repository and Factory patterns, we’ve built a solution that is decoupled, flexible, and future-proof. Whether you're working with a single database or need to scale out to multiple data sources, this design pattern combo provides a clean way to manage your data access logic without locking yourself into a specific implementation.

Now, you're equipped with an approach that allows you to seamlessly manage different databases for your Item API—and all while keeping your code maintainable and easy to extend. What other scenarios could you apply this pattern to? Let’s discuss in the comments!

Are you on page?

Does this pattern combo work well for your needs? Have you encountered situations where managing multiple databases is necessary? Feel free to share your experiences or ask questions below!

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...