Retour à Blog
29 nov. 2025
4 min de lecture

Repository Pattern vs EF Core Direct : Le Grand Débat

Faut-il utiliser le Repository Pattern ou travailler directement avec le DbContext ? Explorez les deux approches à travers des exemples pratiques, des benchmarks de performance et des scénarios réels pour faire le bon choix dans vos projets .NET.
On this page

Repository Pattern vs EF Core Direct : Le Grand Débat – par Adrian Bailador Panero

Introduction

Travailler avec .NET et Entity Framework Core vous mène inévitablement vers l’un des sujets les plus débattus de la communauté : faut-il utiliser le Repository Pattern, ou travailler directement avec le DbContext ? Les avis divergent considérablement, et il peut être difficile de déterminer quelle approche convient à votre application.

Dans cet article, je vous guide à travers les deux options avec des exemples pratiques, des explications claires et un contexte concret. Nous explorerons leurs avantages, leurs inconvénients, leurs différences de performance, et les cas où chaque approche excelle réellement. À la fin, vous serez en mesure de faire un choix pragmatique et informé, adapté aux besoins de vos projets .NET, sans complexité inutile ni sur-ingénierie.

⸻

Table des Matières

  • Comprendre le Repository Pattern
  • L’Approche Directe avec EF Core
  • Les Arguments POUR le Repository Pattern
  • Les Arguments CONTRE le Repository Pattern
  • Comparaison des Performances
  • Scénarios Réels
  • Ma Recommandation
  • Bonnes Pratiques

Comprendre le Repository Pattern

Le Repository Pattern est un patron de conception qui crée une couche d’abstraction entre votre logique métier et votre logique d’accès aux données. Il encapsule la logique nécessaire pour accéder aux sources de données.

Implémentation Basique d’un Repository

// Interface de repository générique
public interface IRepository<T> where T : class
{
    Task<T?> GetByIdAsync(int id);
    Task<IEnumerable<T>> GetAllAsync();
    Task<T> AddAsync(T entity);
    Task UpdateAsync(T entity);
    Task DeleteAsync(int id);
    Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);
}

// Implémentation du repository générique
public class Repository<T> : IRepository<T> where T : class
{
    private readonly ApplicationDbContext _context;
    private readonly DbSet<T> _dbSet;

    public Repository(ApplicationDbContext context)
    {
        _context = context;
        _dbSet = context.Set<T>();
    }

    public async Task<T?> GetByIdAsync(int id)
    {
        return await _dbSet.FindAsync(id);
    }

    public async Task<IEnumerable<T>> GetAllAsync()
    {
        return await _dbSet.ToListAsync();
    }

    public async Task<T> AddAsync(T entity)
    {
        await _dbSet.AddAsync(entity);
        await _context.SaveChangesAsync();
        return entity;
    }

    public async Task UpdateAsync(T entity)
    {
        _dbSet.Update(entity);
        await _context.SaveChangesAsync();
    }

    public async Task DeleteAsync(int id)
    {
        var entity = await GetByIdAsync(id);
        if (entity != null)
        {
            _dbSet.Remove(entity);
            await _context.SaveChangesAsync();
        }
    }

    public async Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate)
    {
        return await _dbSet.Where(predicate).ToListAsync();
    }
}

Repository Spécifique pour les Requêtes Complexes

public interface IOrderRepository : IRepository<Order>
{
    Task<IEnumerable<Order>> GetOrdersByCustomerIdAsync(int customerId);
    Task<IEnumerable<Order>> GetPendingOrdersAsync();
    Task<decimal> GetTotalRevenueByDateRangeAsync(DateTime start, DateTime end);
}

public class OrderRepository : Repository<Order>, IOrderRepository
{
    private readonly ApplicationDbContext _context;

    public OrderRepository(ApplicationDbContext context) : base(context)
    {
        _context = context;
    }

    public async Task<IEnumerable<Order>> GetOrdersByCustomerIdAsync(int customerId)
    {
        return await _context.Orders
            .Include(o => o.OrderItems)
            .ThenInclude(oi => oi.Product)
            .Where(o => o.CustomerId == customerId)
            .OrderByDescending(o => o.OrderDate)
            .ToListAsync();
    }

    public async Task<IEnumerable<Order>> GetPendingOrdersAsync()
    {
        return await _context.Orders
            .Include(o => o.Customer)
            .Where(o => o.Status == OrderStatus.Pending)
            .ToListAsync();
    }

    public async Task<decimal> GetTotalRevenueByDateRangeAsync(DateTime start, DateTime end)
    {
        return await _context.Orders
            .Where(o => o.OrderDate >= start && o.OrderDate <= end)
            .SumAsync(o => o.TotalAmount);
    }
}

Utilisation dans la Couche Service

public class OrderService
{
    private readonly IOrderRepository _orderRepository;

    public OrderService(IOrderRepository orderRepository)
    {
        _orderRepository = orderRepository;
    }

    public async Task<OrderDto> CreateOrderAsync(CreateOrderDto dto)
    {
        var order = new Order
        {
            CustomerId = dto.CustomerId,
            OrderDate = DateTime.UtcNow,
            Status = OrderStatus.Pending,
            TotalAmount = dto.TotalAmount
        };

        var createdOrder = await _orderRepository.AddAsync(order);
        return MapToDto(createdOrder);
    }

    public async Task<IEnumerable<OrderDto>> GetCustomerOrdersAsync(int customerId)
    {
        var orders = await _orderRepository.GetOrdersByCustomerIdAsync(customerId);
        return orders.Select(MapToDto);
    }
}

L’Approche Directe avec EF Core

L’approche directe consiste à utiliser le DbContext directement dans vos services, sans couche d’abstraction.

Service avec DbContext Direct

public class OrderService
{
    private readonly ApplicationDbContext _context;

    public OrderService(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<OrderDto> CreateOrderAsync(CreateOrderDto dto)
    {
        var order = new Order
        {
            CustomerId = dto.CustomerId,
            OrderDate = DateTime.UtcNow,
            Status = OrderStatus.Pending,
            TotalAmount = dto.TotalAmount
        };

        _context.Orders.Add(order);
        await _context.SaveChangesAsync();
        
        return MapToDto(order);
    }

    public async Task<IEnumerable<OrderDto>> GetCustomerOrdersAsync(int customerId)
    {
        var orders = await _context.Orders
            .Include(o => o.OrderItems)
            .ThenInclude(oi => oi.Product)
            .Where(o => o.CustomerId == customerId)
            .OrderByDescending(o => o.OrderDate)
            .ToListAsync();

        return orders.Select(MapToDto);
    }

    public async Task<IEnumerable<OrderDto>> GetPendingOrdersAsync()
    {
        return await _context.Orders
            .Include(o => o.Customer)
            .Where(o => o.Status == OrderStatus.Pending)
            .Select(o => new OrderDto
            {
                Id = o.Id,
                CustomerName = o.Customer.Name,
                OrderDate = o.OrderDate,
                Status = o.Status.ToString(),
                TotalAmount = o.TotalAmount
            })
            .ToListAsync();
    }

    public async Task<decimal> GetTotalRevenueByDateRangeAsync(DateTime start, DateTime end)
    {
        return await _context.Orders
            .Where(o => o.OrderDate >= start && o.OrderDate <= end)
            .SumAsync(o => o.TotalAmount);
    }
}

Les Arguments POUR le Repository Pattern

1. Testabilité

Le Repository Pattern facilite les tests unitaires en permettant de mocker le repository :

public class OrderServiceTests
{
    [Fact]
    public async Task CreateOrder_ShouldReturnOrderDto()
    {
        // Arrange
        var mockRepository = new Mock<IOrderRepository>();
        var expectedOrder = new Order { Id = 1, CustomerId = 1 };
        
        mockRepository
            .Setup(r => r.AddAsync(It.IsAny<Order>()))
            .ReturnsAsync(expectedOrder);

        var service = new OrderService(mockRepository.Object);
        var dto = new CreateOrderDto { CustomerId = 1, TotalAmount = 100 };

        // Act
        var result = await service.CreateOrderAsync(dto);

        // Assert
        Assert.NotNull(result);
        mockRepository.Verify(r => r.AddAsync(It.IsAny<Order>()), Times.Once);
    }
}

2. Séparation des Responsabilités

Séparation claire entre la logique métier et l’accès aux données :

// Couche de logique métier
public class OrderProcessingService
{
    private readonly IOrderRepository _orderRepository;
    private readonly IPaymentService _paymentService;
    private readonly IEmailService _emailService;

    public OrderProcessingService(
        IOrderRepository orderRepository,
        IPaymentService paymentService,
        IEmailService emailService)
    {
        _orderRepository = orderRepository;
        _paymentService = paymentService;
        _emailService = emailService;
    }

    public async Task<bool> ProcessOrderAsync(int orderId)
    {
        // Logique métier ici - claire et ciblée
        var order = await _orderRepository.GetByIdAsync(orderId);
        if (order == null) return false;

        var paymentResult = await _paymentService.ProcessPaymentAsync(order);
        if (!paymentResult.Success) return false;

        order.Status = OrderStatus.Paid;
        await _orderRepository.UpdateAsync(order);

        await _emailService.SendOrderConfirmationAsync(order);
        return true;
    }
}

3. Logique d’Accès aux Données Centralisée

Toutes les requêtes à la base de données au même endroit, ce qui facilite la maintenance :

public class ProductRepository : Repository<Product>, IProductRepository
{
    private readonly ApplicationDbContext _context;

    public ProductRepository(ApplicationDbContext context) : base(context)
    {
        _context = context;
    }

    // Requête complexe centralisée
    public async Task<IEnumerable<Product>> GetActiveProductsWithStockAsync()
    {
        return await _context.Products
            .Include(p => p.Category)
            .Include(p => p.Supplier)
            .Where(p => p.IsActive && p.Stock > 0)
            .OrderBy(p => p.Name)
            .ToListAsync();
    }

    // Si la logique de la requête change, vous ne la mettez à jour qu'ici
    public async Task<IEnumerable<Product>> GetLowStockProductsAsync(int threshold = 10)
    {
        return await _context.Products
            .Where(p => p.IsActive && p.Stock <= threshold)
            .Include(p => p.Supplier)
            .ToListAsync();
    }
}

4. Indépendance par Rapport au Fournisseur de Base de Données

Plus facile de changer entre différentes sources de données :

// L'interface reste identique
public interface ICustomerRepository
{
    Task<Customer?> GetByEmailAsync(string email);
    Task<IEnumerable<Customer>> GetActiveCustomersAsync();
}

// Implémentation SQL Server
public class SqlServerCustomerRepository : ICustomerRepository
{
    private readonly ApplicationDbContext _context;
    
    public async Task<Customer?> GetByEmailAsync(string email)
    {
        return await _context.Customers
            .FirstOrDefaultAsync(c => c.Email == email);
    }
    
    public async Task<IEnumerable<Customer>> GetActiveCustomersAsync()
    {
        return await _context.Customers
            .Where(c => c.IsActive)
            .ToListAsync();
    }
}

// Implémentation MongoDB (hypothétique)
public class MongoCustomerRepository : ICustomerRepository
{
    private readonly IMongoCollection<Customer> _collection;
    
    public async Task<Customer?> GetByEmailAsync(string email)
    {
        return await _collection
            .Find(c => c.Email == email)
            .FirstOrDefaultAsync();
    }
    
    public async Task<IEnumerable<Customer>> GetActiveCustomersAsync()
    {
        return await _collection
            .Find(c => c.IsActive)
            .ToListAsync();
    }
}

Les Arguments CONTRE le Repository Pattern

1. EF Core Est Déjà un Repository Pattern

Le DbContext et le DbSet implémentent déjà les patrons Repository et Unit of Work :

// Le DbContext EST une Unit of Work
public class ApplicationDbContext : DbContext
{
    // Le DbSet<T> EST un Repository
    public DbSet<Order> Orders { get; set; }
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Product> Products { get; set; }

    // SaveChanges gère la transaction
    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        return await base.SaveChangesAsync(cancellationToken);
    }
}

2. Sur-Abstraction et Complexité Inutile

Ajouter une couche de repository peut créer une indirection inutile :

// Avec Repository : 3 couches d'indirection
Controller -> Service -> Repository -> DbContext

// EF Core direct : 2 couches
Controller -> Service (avec DbContext)

// Exemple de sur-abstraction
public class CustomerRepository : ICustomerRepository
{
    private readonly ApplicationDbContext _context;
    
    // Cette méthode se contente littéralement d'envelopper le DbContext
    public async Task<Customer?> GetByIdAsync(int id)
    {
        return await _context.Customers.FindAsync(id); // Wrapper inutile
    }
}

3. Perte des Fonctionnalités Avancées d’EF Core

Les repositories peuvent masquer des fonctionnalités puissantes d’EF Core :

// EF Core direct - Toute la puissance d'IQueryable
public async Task<PagedResult<ProductDto>> GetProductsAsync(ProductFilter filter)
{
    IQueryable<Product> query = _context.Products
        .Include(p => p.Category)
        .AsQueryable();

    // Filtrage dynamique
    if (!string.IsNullOrEmpty(filter.CategoryName))
        query = query.Where(p => p.Category.Name == filter.CategoryName);

    if (filter.MinPrice.HasValue)
        query = query.Where(p => p.Price >= filter.MinPrice.Value);

    if (filter.MaxPrice.HasValue)
        query = query.Where(p => p.Price <= filter.MaxPrice.Value);

    // Projection efficace - ne sélectionne que les colonnes nécessaires
    var pagedQuery = query
        .OrderBy(p => p.Name)
        .Skip((filter.Page - 1) * filter.PageSize)
        .Take(filter.PageSize)
        .Select(p => new ProductDto
        {
            Id = p.Id,
            Name = p.Name,
            Price = p.Price,
            CategoryName = p.Category.Name
        });

    var items = await pagedQuery.ToListAsync();
    var totalCount = await query.CountAsync();

    return new PagedResult<ProductDto>
    {
        Items = items,
        TotalCount = totalCount,
        Page = filter.Page,
        PageSize = filter.PageSize
    };
}

// Avec Repository - Il faudrait exposer IQueryable ou créer d'innombrables méthodes
public interface IProductRepository
{
    IQueryable<Product> GetQueryable(); // Abstraction qui fuit
    // OU
    Task<IEnumerable<Product>> GetByCategoryAsync(string category);
    Task<IEnumerable<Product>> GetByPriceRangeAsync(decimal min, decimal max);
    Task<IEnumerable<Product>> GetByCategoryAndPriceAsync(string category, decimal min, decimal max);
    // ... combinaisons infinies
}

4. Tester EF Core Est Plus Facile Qu’il n’y Paraît

Avec le fournisseur InMemory ou SQLite, les tests sont simples :

public class OrderServiceTests
{
    private ApplicationDbContext CreateDbContext()
    {
        var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
            .Options;

        return new ApplicationDbContext(options);
    }

    [Fact]
    public async Task GetPendingOrders_ShouldReturnOnlyPendingOrders()
    {
        // Arrange
        await using var context = CreateDbContext();
        context.Orders.AddRange(
            new Order { Id = 1, Status = OrderStatus.Pending },
            new Order { Id = 2, Status = OrderStatus.Completed },
            new Order { Id = 3, Status = OrderStatus.Pending }
        );
        await context.SaveChangesAsync();

        var service = new OrderService(context);

        // Act
        var result = await service.GetPendingOrdersAsync();

        // Assert
        Assert.Equal(2, result.Count());
        Assert.All(result, o => Assert.Equal("Pending", o.Status));
    }
}

5. Surcoût de Performance

Chaque abstraction ajoute une surcharge :

// Approche Repository - Plusieurs couches d'exécution
var orders = await _orderRepository.GetOrdersByCustomerIdAsync(customerId);
// Exécution : Controller -> Service -> Repository -> DbContext -> Base de données

// DbContext direct - Moins de couches
var orders = await _context.Orders
    .Where(o => o.CustomerId == customerId)
    .ToListAsync();
// Exécution : Controller -> Service (DbContext) -> Base de données

Comparaison des Performances

Regardons un benchmark réel comparant les deux approches :

[MemoryDiagnoser]
public class RepositoryVsDirectBenchmark
{
    private ApplicationDbContext _context;
    private IOrderRepository _repository;

    [GlobalSetup]
    public void Setup()
    {
        var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseInMemoryDatabase("BenchmarkDb")
            .Options;

        _context = new ApplicationDbContext(options);
        _repository = new OrderRepository(_context);

        // Données initiales (seed)
        for (int i = 1; i <= 1000; i++)
        {
            _context.Orders.Add(new Order
            {
                Id = i,
                CustomerId = i % 100,
                OrderDate = DateTime.UtcNow.AddDays(-i),
                TotalAmount = i * 10
            });
        }
        _context.SaveChanges();
    }

    [Benchmark]
    public async Task<int> WithRepository()
    {
        var orders = await _repository.FindAsync(o => o.CustomerId == 50);
        return orders.Count();
    }

    [Benchmark]
    public async Task<int> WithDirectDbContext()
    {
        var orders = await _context.Orders
            .Where(o => o.CustomerId == 50)
            .ToListAsync();
        return orders.Count;
    }

    [Benchmark]
    public async Task<int> WithDirectDbContext_Projection()
    {
        // Le plus efficace - ne sélectionne que les données nécessaires
        return await _context.Orders
            .Where(o => o.CustomerId == 50)
            .CountAsync();
    }
}

/*
Résultats (typiques) :
|                        Method |     Mean |   Error |  StdDev |  Gen 0 | Allocated |
|------------------------------ |---------:|--------:|--------:|-------:|----------:|
|                WithRepository | 125.4 μs | 2.1 μs  | 1.9 μs  | 2.4414 |   15.6 KB |
|          WithDirectDbContext  | 118.2 μs | 1.8 μs  | 1.6 μs  | 2.1973 |   14.2 KB |
| WithDirectDbContext_Projection|  95.3 μs | 1.2 μs  | 1.1 μs  | 0.9766 |    6.1 KB |
*/

Scénarios Réels

Scénario 1 : Application CRUD Simple

Meilleur Choix : EF Core Direct

// Pour un blog simple ou une app de tâches, les repositories ajoutent une complexité inutile
public class BlogPostService
{
    private readonly ApplicationDbContext _context;

    public BlogPostService(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<IEnumerable<BlogPostDto>> GetRecentPostsAsync(int count = 10)
    {
        return await _context.BlogPosts
            .Include(p => p.Author)
            .Include(p => p.Category)
            .Where(p => p.IsPublished)
            .OrderByDescending(p => p.PublishedDate)
            .Take(count)
            .Select(p => new BlogPostDto
            {
                Id = p.Id,
                Title = p.Title,
                Excerpt = p.Content.Substring(0, 200),
                AuthorName = p.Author.Name,
                CategoryName = p.Category.Name,
                PublishedDate = p.PublishedDate
            })
            .ToListAsync();
    }
}

Scénario 2 : Application d’Entreprise Complexe

Meilleur Choix : Repository Pattern (avec réserves)

// Équipes multiples, logique métier complexe, besoin d'abstraction
public interface IOrderRepository
{
    Task<Order?> GetOrderWithDetailsAsync(int orderId);
    Task<IEnumerable<Order>> GetOrdersByStatusAsync(OrderStatus status);
    Task<OrderStatistics> GetOrderStatisticsAsync(DateTime from, DateTime to);
}

public class OrderProcessingService
{
    private readonly IOrderRepository _orderRepository;
    private readonly IPaymentRepository _paymentRepository;
    private readonly IInventoryRepository _inventoryRepository;
    private readonly INotificationService _notificationService;

    public OrderProcessingService(
        IOrderRepository orderRepository,
        IPaymentRepository paymentRepository,
        IInventoryRepository inventoryRepository,
        INotificationService notificationService)
    {
        _orderRepository = orderRepository;
        _paymentRepository = paymentRepository;
        _inventoryRepository = inventoryRepository;
        _notificationService = notificationService;
    }

    public async Task<ProcessOrderResult> ProcessOrderAsync(int orderId)
    {
        var order = await _orderRepository.GetOrderWithDetailsAsync(orderId);
        if (order == null)
            return ProcessOrderResult.NotFound();

        // Logique métier complexe coordonnant plusieurs repositories
        var inventoryCheck = await _inventoryRepository.CheckAvailabilityAsync(order.OrderItems);
        if (!inventoryCheck.AllAvailable)
            return ProcessOrderResult.InsufficientInventory(inventoryCheck.UnavailableItems);

        var payment = await _paymentRepository.ProcessPaymentAsync(order);
        if (!payment.Success)
            return ProcessOrderResult.PaymentFailed(payment.ErrorMessage);

        await _inventoryRepository.ReserveItemsAsync(order.OrderItems);
        order.Status = OrderStatus.Processing;
        await _orderRepository.UpdateAsync(order);

        await _notificationService.SendOrderConfirmationAsync(order);

        return ProcessOrderResult.Success(order);
    }
}

Scénario 3 : Architecture Microservices

Meilleur Choix : Approche Hybride

// Utilisez des repositories pour les préoccupations transversales, DbContext direct pour les requêtes simples
public class OrderService
{
    private readonly ApplicationDbContext _context;
    private readonly ICacheRepository _cacheRepository;
    private readonly IAuditRepository _auditRepository;

    public OrderService(
        ApplicationDbContext context,
        ICacheRepository cacheRepository,
        IAuditRepository auditRepository)
    {
        _context = context;
        _cacheRepository = cacheRepository;
        _auditRepository = auditRepository;
    }

    public async Task<OrderDto?> GetOrderAsync(int orderId)
    {
        // Vérifiez d'abord le cache (repository pour préoccupation transversale)
        var cached = await _cacheRepository.GetAsync<OrderDto>($"order:{orderId}");
        if (cached != null)
            return cached;

        // DbContext direct pour l'accès aux données
        var order = await _context.Orders
            .Include(o => o.Customer)
            .Include(o => o.OrderItems)
            .FirstOrDefaultAsync(o => o.Id == orderId);

        if (order == null)
            return null;

        var dto = MapToDto(order);

        // Mettez le résultat en cache
        await _cacheRepository.SetAsync($"order:{orderId}", dto, TimeSpan.FromMinutes(10));

        return dto;
    }

    public async Task<Order> CreateOrderAsync(CreateOrderDto createDto)
    {
        var order = MapToOrder(createDto);

        _context.Orders.Add(order);
        await _context.SaveChangesAsync();

        // Journalisation d'audit via le repository
        await _auditRepository.LogAsync(new AuditEntry
        {
            EntityType = nameof(Order),
            EntityId = order.Id.ToString(),
            Action = "Create",
            Timestamp = DateTime.UtcNow
        });

        return order;
    }
}

Ma Recommandation : L’Approche Pragmatique

Après des années à travailler avec les deux approches, voici mon avis :

Utilisez EF Core Direct Quand :

  1. Applications simples - opérations CRUD, petites équipes
  2. Prototypes ou MVP - la vitesse de développement compte davantage
  3. Opérations à forte lecture - vous avez besoin de toute la puissance d’IQueryable
  4. La performance est critique - chaque couche ajoute une surcharge
  5. Petite équipe - tout le monde maîtrise bien EF Core
// Simple, propre, efficace
public class ProductService
{
    private readonly ApplicationDbContext _context;

    public ProductService(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<IEnumerable<ProductDto>> SearchProductsAsync(string searchTerm)
    {
        return await _context.Products
            .Where(p => p.Name.Contains(searchTerm) || p.Description.Contains(searchTerm))
            .Select(p => new ProductDto
            {
                Id = p.Id,
                Name = p.Name,
                Price = p.Price
            })
            .ToListAsync();
    }
}

Utilisez le Repository Pattern Quand :

  1. Logique métier complexe - sources de données multiples, transactions complexes
  2. Grandes équipes - besoin de limites et de contrats clairs
  3. Sources de données multiples - SQL + NoSQL + API externes
  4. Exigences de tests poussées - besoin de mocker facilement la couche de données
  5. Domain-Driven Design - en suivant les principes du DDD
// Abstraction claire pour les scénarios complexes
public interface IOrderRepository
{
    Task<Order?> GetByIdWithFullDetailsAsync(int orderId);
    Task<IEnumerable<Order>> GetOrdersRequiringAttentionAsync();
    Task<bool> CanFulfillOrderAsync(Order order);
}

public class OrderRepository : IOrderRepository
{
    private readonly ApplicationDbContext _context;
    private readonly IInventoryService _inventoryService;

    public async Task<bool> CanFulfillOrderAsync(Order order)
    {
        // Logique complexe combinant des requêtes de base de données et des appels à des services externes
        var items = await _context.OrderItems
            .Where(oi => oi.OrderId == order.Id)
            .Include(oi => oi.Product)
            .ToListAsync();

        foreach (var item in items)
        {
            var available = await _inventoryService.CheckStockAsync(item.ProductId, item.Quantity);
            if (!available)
                return false;
        }

        return true;
    }
}

L’Approche Hybride (Ma Préférée)

// Utilisez des repositories SEULEMENT quand ils apportent de la valeur
public class OrderService
{
    private readonly ApplicationDbContext _context;
    private readonly ISpecificationEvaluator _specificationEvaluator;

    public OrderService(ApplicationDbContext context, ISpecificationEvaluator specificationEvaluator)
    {
        _context = context;
        _specificationEvaluator = specificationEvaluator;
    }

    // Requêtes simples : DbContext direct
    public async Task<Order?> GetOrderByIdAsync(int id)
    {
        return await _context.Orders
            .Include(o => o.Customer)
            .FirstOrDefaultAsync(o => o.Id == id);
    }

    // Requêtes complexes : utilisez le Specification Pattern (abstraction légère)
    public async Task<IEnumerable<Order>> GetOrdersAsync(ISpecification<Order> specification)
    {
        return await _specificationEvaluator
            .GetQuery(_context.Orders, specification)
            .ToListAsync();
    }
}

// Specification Pattern - logique de requête réutilisable sans repository complet
public class OrdersWithItemsSpecification : Specification<Order>
{
    public OrdersWithItemsSpecification(int customerId)
    {
        AddInclude(o => o.OrderItems);
        AddInclude("OrderItems.Product");
        AddCriteria(o => o.CustomerId == customerId);
        ApplyOrderByDescending(o => o.OrderDate);
    }
}

Bonnes Pratiques

1. Ne Laissez Pas Fuiter IQueryable Depuis les Repositories

// MAUVAIS - Abstraction qui fuit
public interface IProductRepository
{
    IQueryable<Product> GetAll();
}

// BON - Requête encapsulée
public interface IProductRepository
{
    Task<IEnumerable<Product>> GetActiveProductsAsync();
    Task<IEnumerable<Product>> SearchAsync(string searchTerm);
}

2. Utilisez des Specifications pour les Requêtes Complexes

public interface ISpecification<T>
{
    Expression<Func<T, bool>>? Criteria { get; }
    List<Expression<Func<T, object>>> Includes { get; }
    List<string> IncludeStrings { get; }
}

public class ActiveProductsWithCategorySpecification : ISpecification<Product>
{
    public Expression<Func<Product, bool>> Criteria => p => p.IsActive;

    public List<Expression<Func<Product, object>>> Includes { get; } = new()
    {
        p => p.Category
    };

    public List<string> IncludeStrings { get; } = new();
}

3. Évitez les Repositories Génériques pour Tout

// MAUVAIS - Repository générique essayant de tout faire
public class Repository<T> : IRepository<T> where T : class
{
    // Plus de 50 méthodes essayant de couvrir tous les scénarios possibles
}

// BON - Repositories spécifiques pour des besoins spécifiques
public interface IOrderRepository
{
    Task<Order?> GetByIdAsync(int id);
    Task<IEnumerable<Order>> GetPendingOrdersAsync();
    Task<OrderStatistics> GetStatisticsAsync(DateTime from, DateTime to);
    // Seulement les méthodes dont vous avez réellement besoin
}

4. Envisagez d’Utiliser MediatR pour les Opérations Complexes

// Séparation propre sans couche de repository lourde
public class GetOrderByIdQuery : IRequest<OrderDto?>
{
    public int OrderId { get; set; }
}

public class GetOrderByIdQueryHandler : IRequestHandler<GetOrderByIdQuery, OrderDto?>
{
    private readonly ApplicationDbContext _context;

    public GetOrderByIdQueryHandler(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<OrderDto?> Handle(GetOrderByIdQuery request, CancellationToken cancellationToken)
    {
        return await _context.Orders
            .Include(o => o.Customer)
            .Where(o => o.Id == request.OrderId)
            .Select(o => new OrderDto
            {
                Id = o.Id,
                CustomerName = o.Customer.Name,
                TotalAmount = o.TotalAmount
            })
            .FirstOrDefaultAsync(cancellationToken);
    }
}

Conclusion

Il n’y a pas de réponse universelle au débat Repository vs EF Core Direct. La meilleure approche dépend de votre scénario spécifique :

  • Petits projets, CRUD simple : EF Core direct est plus propre et plus rapide
  • Grandes applications d’entreprise : le Repository Pattern apporte de la structure
  • La plupart des applications réelles : une approche hybride fonctionne le mieux

Mon conseil : commencez simplement avec le DbContext direct. Ajoutez des repositories uniquement quand vous avez réellement besoin de l’abstraction. Ne sur-ingénierisez pas prématurément, mais n’ayez pas peur de refactoriser quand la complexité l’exige.

Rappelez-vous : EF Core est déjà bien conçu. Respectez ses patrons, et n’abstrayez que lorsque vous apportez une réelle valeur, pas seulement des couches.

Quelle approche préférez-vous ? Dites-le moi dans les commentaires !


Pour Aller Plus Loin :

Subscribe
Get new posts by email

No spam, unsubscribe anytime.