Implementing Midia Repository In .NET

by Alex Johnson 38 views

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 Midia entity.
    • Defines the IMidiaRepositorio interface, which includes methods for adding, retrieving, listing, and updating media.
  • CatalogoDeMidia.Infraestrutura:
    • Includes the CatalogoDeMidiaDbContext for database interactions.
    • Defines the MidiaConfiguracao for EF Core configurations.
    • Implements the concrete MidiaRepositorio, which implements IMidiaRepositorio.

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.md
  • instructions/40-estrutura-da-solution-e-detalhamento.md
  • Any specific repository instructions (e.g., instructions/50-persistencia-e-repositorios.md).
  • The file where IMidiaRepositorio is defined.

Objective

Our primary goal is to create the MidiaRepositorio in CatalogoDeMidia.Infraestrutura. This repository will:

  • Implement the IMidiaRepositorio interface.
  • Use CatalogoDeMidiaDbContext to access the Midia table.
  • Apply EF Core best practices, such as asynchronous queries, using AsNoTracking() where appropriate, and respecting the CancellationToken.
  • Be ready for registration in Dependency Injection (DI) via ConfiguracaoInfraestruturaExtensoes.

Responsibilities of the Repository

The MidiaRepositorio class should:

  1. 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.
  2. Utilize CatalogoDeMidiaDbContext: Inject the context via the constructor and use _dbContext.Midias as 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.

  3. Respect layer conventions: Avoid exposing EF Core-specific types (like DbSet or IQueryable) 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.

  4. Implement efficient queries: Use AsNoTracking() for read-only queries to improve performance. Implement filters appropriately (e.g., by TipoMidia, GeneroMidia, or partial title) as defined in the interface. Efficient queries are crucial for application performance, particularly as data volume grows. This includes carefully crafting WHERE clauses and leveraging indexes in the database.

  5. Apply asynchronicity: All database access methods should be asynchronous (async/await), using methods like ToListAsync, FirstOrDefaultAsync, and FindAsync. Handle and pass the CancellationToken to EF Core calls. Asynchronous operations prevent blocking the main thread, which is especially important in web applications to maintain responsiveness and scalability. The CancellationToken enables graceful cancellation of operations, further enhancing application robustness.

Technical Requirements

1. Location and Namespace

  • Create the MidiaRepositorio class within CatalogoDeMidia.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.Midias for operations involving the Midia entity.
  • 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 CancellationToken to all asynchronous calls.

5. Return Patterns

  • Use return types as defined in the interface, such as Task<Midia?> or Task<IReadOnlyCollection<Midia>>.
  • Avoid returning DbSet or IQueryable in 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

  1. Review the instructions: Familiarize yourself with the complete IMidiaRepositorio signature, repository patterns (e.g., returning readonly collections, usage of specifications), and transaction management (whether the repository controls SaveChanges or if there's a separate unit of work).

  2. Examine IMidiaRepositorio: Open the IMidiaRepositorio interface in CatalogoDeMidia.Dominio and list all methods that need implementation. This ensures you cover all required functionalities.

  3. Create MidiaRepositorio.cs: Add the MidiaRepositorio.cs file to the CatalogoDeMidia.Infraestrutura project within the appropriate namespace, ensuring it aligns with the project's structure.

  4. Implement MidiaRepositorio: Implement the class, injecting CatalogoDeMidiaDbContext via the constructor and implementing all methods from IMidiaRepositorio using EF Core.

  5. 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.
  6. 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.cs exists in CatalogoDeMidia.Infraestrutura in the correct namespace.
  • [ ] The MidiaRepositorio class implements IMidiaRepositorio.
  • [ ] The class receives CatalogoDeMidiaDbContext via dependency injection.
  • [ ] All methods defined in IMidiaRepositorio are implemented.
  • [ ] Read methods use EF Core asynchronously, preferably with AsNoTracking() when tracking is unnecessary.
  • [ ] Write methods (Adicionar, Atualizar, Remover) use the DbContext correctly.
  • [ ] The repository does not expose EF Core-specific types in its domain interface.
  • [ ] The implementation is compatible with DI registration (e.g., IMidiaRepositorio → MidiaRepositorio via AddScoped).

References

  • instructions/20-arquitetura-ddd-e-dependencias.md
  • instructions/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.