Skip to main content

Lesson 5 of 8

Service Layer Design Patterns

The service layer contains business logic - orchestrating repositories, applying rules, publishing events, and returning results. Services should be thin orchestrators, not controllers rewriting the repository logic.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Rich Service Layer with Domain Events

Rich Service Layer with Domain Events
// Application/Services/ProductService.cs
public class ProductService(
    IUnitOfWork uow,
    IMapper mapper,
    IValidator<CreateProductRequest> validator,
    IMediator mediator,
    ILogger<ProductService> logger)
{
    public async Task<Result<ProductResponse>> CreateAsync(
        CreateProductRequest request, CancellationToken ct)
    {
        // 1. Validate
        var validation = await validator.ValidateAsync(request, ct);
        if (!validation.IsValid)
            return Result<ProductResponse>.Validation(
                validation.Errors.Select(e => e.ErrorMessage).ToArray());

        // 2. Check business rules
        var slugConflict = await uow.Products.SlugExistsAsync(
            SlugOf(request.Name), ct: ct);
        if (slugConflict)
            return Result<ProductResponse>.Conflict($"Product '{request.Name}' already exists");

        // 3. Map to entity
        var product = mapper.Map<Product>(request);

        // 4. Persist
        uow.Products.Add(product);
        await uow.SaveChangesAsync(ct);

        // 5. Publish domain event
        await mediator.Publish(new ProductCreatedEvent(product.Id, product.Name), ct);

        logger.LogInformation("Product {ProductId} '{ProductName}' created", product.Id, product.Name);

        // 6. Return DTO
        return Result<ProductResponse>.Success(mapper.Map<ProductResponse>(product));
    }

    public async Task<Result<ProductResponse>> UpdatePriceAsync(
        Guid id, decimal newPrice, CancellationToken ct)
    {
        var product = await uow.Products.FindByIdAsync(id, ct);
        if (product is null)
            return Result<ProductResponse>.NotFound(nameof(Product), id);

        // Business rule: can't increase price by more than 50% at once
        if (newPrice > product.Price * 1.5m)
            return Result<ProductResponse>.Validation("Price increase cannot exceed 50% in one update");

        product.Price = newPrice;
        uow.Products.Update(product);
        await uow.SaveChangesAsync(ct);

        return Result<ProductResponse>.Success(mapper.Map<ProductResponse>(product));
    }

    private static string SlugOf(string name) => name.ToLower().Replace(" ", "-").Trim();
}

// Domain event
public record ProductCreatedEvent(Guid ProductId, string ProductName) : INotification;

// Event handler - send welcome email, update search index, etc.
public class ProductCreatedEventHandler(ILogger<ProductCreatedEventHandler> logger)
    : INotificationHandler<ProductCreatedEvent>
{
    public Task Handle(ProductCreatedEvent notification, CancellationToken ct)
    {
        logger.LogInformation("Product created event handled: {ProductId}", notification.ProductId);
        return Task.CompletedTask;
    }
}

// Result<T> extended version
class Result<T>
{
    public bool IsSuccess { get; private set; }
    public T? Value { get; private set; }
    public string? Error { get; private set; }
    public ResultErrorType ErrorType { get; private set; }

    private Result() { }

    public static Result<T> Success(T v) => new() { IsSuccess = true, Value = v };
    public static Result<T> Validation(string[] e) => new() { Error = string.Join("; ", e), ErrorType = ResultErrorType.Validation };
    public static Result<T> Conflict(string e) => new() { Error = e, ErrorType = ResultErrorType.Conflict };
    public static Result<T> NotFound(string resource, object id) => new() { Error = $"{resource} {id} not found", ErrorType = ResultErrorType.NotFound };
}
enum ResultErrorType { Validation, Conflict, NotFound, Unauthorized }
interface IMediator { Task Publish<T>(T notification, CancellationToken ct); }
interface INotification { }
interface INotificationHandler<T> { Task Handle(T n, CancellationToken ct); }
interface IMapper { TDest Map<TDest>(object src); }
interface IUnitOfWork { IProductRepository Products { get; } Task<int> SaveChangesAsync(CancellationToken ct); }
interface IProductRepository { Task<Product?> FindByIdAsync(Guid id, CancellationToken ct); void Add(Product p); void Update(Product p); Task<bool> SlugExistsAsync(string slug, CancellationToken ct = default); }
class Product { public Guid Id { get; set; } public string Name { get; set; } = ""; public string Slug { get; set; } = ""; public decimal Price { get; set; } public int StockQuantity { get; set; } }
record ProductResponse(Guid Id, string Name, string Slug, decimal Price, string CurrencyCode, string CategoryName, int StockQuantity, bool IsAvailable, DateTime CreatedAt);
record CreateProductRequest(string Name, decimal Price, string CurrencyCode, Guid CategoryId, int InitialStock, string? Description);

Tip

Tip

Practice Service Layer Design Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Service Layer Design Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Service Layer Design Patterns is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done