Implementing Midia Repository In .NET
This article guides you through implementing the MidiaRepositorio repository within the CatalogoDeMidia.Infraestrutura layer. This repository serves as a concrete implementation of the IMidiaRepositorio interface, which is defined in the domain layer. By using EF Core and CatalogoDeMidiaDbContext, we will ensure proper data access and persistence for the Midia entity.
Context
In this project, the domain defines the IMidiaRepositorio interface. This interface abstracts data access and persistence for the Midia entity. The Infrastructure layer provides a concrete implementation of this interface, leveraging EF Core with CatalogoDeMidiaDbContext.
Within the DDD architecture of the CatalogoDeMidia.sln solution:
CatalogoDeMidia.Dominio:- Contains the
Midiaentity. - Defines the
IMidiaRepositoriointerface, which includes methods for adding, retrieving, listing, and updating media.
- Contains the
CatalogoDeMidia.Infraestrutura:- Includes the
CatalogoDeMidiaDbContextfor database interactions. - Defines the
MidiaConfiguracaofor EF Core configurations. - Implements the concrete
MidiaRepositorio, which implementsIMidiaRepositorio.
- Includes the
The instructions folder specifies:
- The implementation pattern for repositories.
- Naming conventions to maintain consistency.
- Expected signatures in
IMidiaRepositorio. - Query patterns, including considerations for tracking, pagination, and filters.
- Return patterns, such as returning collections as
IReadOnlyCollection<Midia>.
Key files to reference include:
instructions/20-arquitetura-ddd-e-dependencias.mdinstructions/40-estrutura-da-solution-e-detalhamento.md- Any specific repository instructions (e.g.,
instructions/50-persistencia-e-repositorios.md). - The file where
IMidiaRepositoriois defined.
Objective
Our primary goal is to create the MidiaRepositorio in CatalogoDeMidia.Infraestrutura. This repository will:
- Implement the
IMidiaRepositoriointerface. - Use
CatalogoDeMidiaDbContextto access theMidiatable. - Apply EF Core best practices, such as asynchronous queries, using
AsNoTracking()where appropriate, and respecting theCancellationToken. - Be ready for registration in Dependency Injection (DI) via
ConfiguracaoInfraestruturaExtensoes.
Responsibilities of the Repository
The MidiaRepositorio class should:
-
Implement all methods defined in
IMidiaRepositorio. This includes:Task<Midia?> ObterPorIdAsync(Guid id, CancellationToken cancellationToken = default);Task AdicionarAsync(Midia midia, CancellationToken cancellationToken = default);Task AtualizarAsync(Midia midia, CancellationToken cancellationToken = default);Task RemoverAsync(Midia midia, CancellationToken cancellationToken = default);- Query methods based on filters like type, genre, and title, if specified in the interface.
-
Utilize
CatalogoDeMidiaDbContext: Inject the context via the constructor and use_dbContext.Midiasas the source for queries. Ensure proper injection to prevent runtime errors and maintain a clean architecture. The context is the entry point to the database, so its correct usage is vital for all repository operations. -
Respect layer conventions: Avoid exposing EF Core-specific types (like
DbSetorIQueryable) outside the repository. Adhere to the established transaction handling approach, whether it involves a unit of work or a more external transaction policy. Following these conventions ensures that the domain remains decoupled from infrastructure concerns. -
Implement efficient queries: Use
AsNoTracking()for read-only queries to improve performance. Implement filters appropriately (e.g., byTipoMidia,GeneroMidia, or partial title) as defined in the interface. Efficient queries are crucial for application performance, particularly as data volume grows. This includes carefully craftingWHEREclauses and leveraging indexes in the database. -
Apply asynchronicity: All database access methods should be asynchronous (
async/await), using methods likeToListAsync,FirstOrDefaultAsync, andFindAsync. Handle and pass theCancellationTokento EF Core calls. Asynchronous operations prevent blocking the main thread, which is especially important in web applications to maintain responsiveness and scalability. TheCancellationTokenenables graceful cancellation of operations, further enhancing application robustness.
Technical Requirements
1. Location and Namespace
-
Create the
MidiaRepositorioclass withinCatalogoDeMidia.Infraestrutura. -
Use a specific namespace for repositories, such as:
namespace CatalogoDeMidia.Infraestrutura.Repositorios; -
Adjust according to the folder and namespace standards defined in the
instructions.
2. Class Signature
-
Implement the domain interface:
public class MidiaRepositorio : IMidiaRepositorio { private readonly CatalogoDeMidiaDbContext _dbContext; public MidiaRepositorio(CatalogoDeMidiaDbContext dbContext) { _dbContext = dbContext; } // Implementation of methods... }
3. Usage of CatalogoDeMidiaDbContext
- Utilize
_dbContext.Midiasfor operations involving theMidiaentity. - For write operations, use
AddAsync,Update,Remove, etc. - For read operations, use
AsNoTracking().Where(...).ToListAsync(...), etc.
4. Asynchronicity and CancellationToken
-
Ensure all EF methods are asynchronous. For example:
await _dbContext.Midias.FindAsync(new object[] { id }, cancellationToken); await _dbContext.Midias.AsNoTracking().ToListAsync(cancellationToken); -
Propagate the
CancellationTokento all asynchronous calls.
5. Return Patterns
- Use return types as defined in the interface, such as
Task<Midia?>orTask<IReadOnlyCollection<Midia>>. - Avoid returning
DbSetorIQueryablein the domain interface.
6. Error Handling
- Do not catch and suppress database exceptions without proper handling.
- Follow the exception handling patterns described in the
instructions. - Relaunch exceptions or convert specific exceptions if a domain/application exception pattern exists.
Step-by-Step Implementation
-
Review the
instructions: Familiarize yourself with the completeIMidiaRepositoriosignature, repository patterns (e.g., returning readonly collections, usage of specifications), and transaction management (whether the repository controlsSaveChangesor if there's a separate unit of work). -
Examine
IMidiaRepositorio: Open theIMidiaRepositoriointerface inCatalogoDeMidia.Dominioand list all methods that need implementation. This ensures you cover all required functionalities. -
Create
MidiaRepositorio.cs: Add theMidiaRepositorio.csfile to theCatalogoDeMidia.Infraestruturaproject within the appropriate namespace, ensuring it aligns with the project's structure. -
Implement
MidiaRepositorio: Implement the class, injectingCatalogoDeMidiaDbContextvia the constructor and implementing all methods fromIMidiaRepositoriousing EF Core. -
Ensure Correctness:
- Verify that all asynchronous methods use
async/await. - Ensure all database accesses receive a
CancellationToken. - Use
AsNoTracking()in read queries when appropriate to avoid unnecessary tracking overhead.
- Verify that all asynchronous methods use
-
Validate Compilation: Check for compilation errors and adjust namespaces/references as needed. This step confirms that the code adheres to project standards and dependencies.
Acceptance Criteria
- [ ]
MidiaRepositorio.csexists inCatalogoDeMidia.Infraestruturain the correct namespace. - [ ] The
MidiaRepositorioclass implementsIMidiaRepositorio. - [ ] The class receives
CatalogoDeMidiaDbContextvia dependency injection. - [ ] All methods defined in
IMidiaRepositorioare implemented. - [ ] Read methods use EF Core asynchronously, preferably with
AsNoTracking()when tracking is unnecessary. - [ ] Write methods (
Adicionar,Atualizar,Remover) use theDbContextcorrectly. - [ ] The repository does not expose EF Core-specific types in its domain interface.
- [ ] The implementation is compatible with DI registration (e.g.,
IMidiaRepositorio→MidiaRepositorioviaAddScoped).
References
instructions/20-arquitetura-ddd-e-dependencias.mdinstructions/40-estrutura-da-solution-e-detalhamento.md- Domain Interface:
IMidiaRepositorio - Entity:
Midia - Infrastructure:
CatalogoDeMidiaDbContext - EF Core:
Microsoft.EntityFrameworkCore- Asynchronous Methods (
ToListAsync,FirstOrDefaultAsync, etc.)
By following these steps and guidelines, you will be able to successfully implement the MidiaRepositorio in your .NET application, adhering to DDD principles and EF Core best practices. Remember to always consult the project's specific instructions for any deviations or additional requirements.
For more information on implementing repositories with EF Core, visit the Microsoft's official documentation.