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
Post a Comment