본문으로 건너뛰기
cccskills
무료GitHub에 공개

dotnet-specification-pattern

Implements the Specification pattern for encapsulating query logic. Enables composable, reusable, and testable query criteria with support for includes, ordering, and pagination.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md7.4 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Specification Pattern Generator

Overview

The Specification pattern encapsulates query logic:

  • Reusable criteria - Define once, use everywhere
  • Composable - Combine with And/Or
  • Testable - Test query logic in isolation
  • Type-safe - Compile-time checking

Quick Reference

ComponentPurpose
ISpecification<T>Base specification interface
BaseSpecification<T>Abstract implementation
SpecificationEvaluatorApplies spec to IQueryable

Template: Specification Interface

// src/{name}.domain/Abstractions/ISpecification.cs
using System.Linq.Expressions;

namespace {name}.domain.abstractions;

public interface ISpecification<T>
{
    Expression<Func<T, bool>>? Criteria { get; }
    List<Expression<Func<T, object>>> Includes { get; }
    List<string> IncludeStrings { get; }
    Expression<Func<T, object>>? OrderBy { get; }
    Expression<Func<T, object>>? OrderByDescending { get; }
    int? Take { get; }
    int? Skip { get; }
    bool IsPagingEnabled { get; }
}

Template: Base Specification

// src/{name}.domain/Abstractions/BaseSpecification.cs
using System.Linq.Expressions;

namespace {name}.domain.abstractions;

public abstract class BaseSpecification<T> : ISpecification<T>
{
    public Expression<Func<T, bool>>? Criteria { get; private set; }
    public List<Expression<Func<T, object>>> Includes { get; } = new();
    public List<string> IncludeStrings { get; } = new();
    public Expression<Func<T, object>>? OrderBy { get; private set; }
    public Expression<Func<T, object>>? OrderByDescending { get; private set; }
    public int? Take { get; private set; }
    public int? Skip { get; private set; }
    public bool IsPagingEnabled { get; private set; }

    protected void AddCriteria(Expression<Func<T, bool>> criteria) => Criteria = criteria;

    protected void AddInclude(Expression<Func<T, object>> include) => Includes.Add(include);

    protected void AddInclude(string include) => IncludeStrings.Add(include);

    protected void ApplyOrderBy(Expression<Func<T, object>> orderBy) => OrderBy = orderBy;

    protected void ApplyOrderByDescending(Expression<Func<T, object>> orderBy) => OrderByDescending = orderBy;

    protected void ApplyPaging(int skip, int take)
    {
        Skip = skip;
        Take = take;
        IsPagingEnabled = true;
    }
}

Template: Concrete Specifications

// src/{name}.domain/{Aggregate}/Specifications/Active{Entities}Specification.cs
namespace {name}.domain.{aggregate}.specifications;

public sealed class Active{Entities}Specification : BaseSpecification<{Entity}>
{
    public Active{Entities}Specification()
    {
        AddCriteria(e => e.IsActive);
        ApplyOrderBy(e => e.Name);
    }
}

public sealed class {Entities}ByOrganizationSpecification : BaseSpecification<{Entity}>
{
    public {Entities}ByOrganizationSpecification(Guid organizationId, bool includeChildren = false)
    {
        AddCriteria(e => e.OrganizationId == organizationId && e.IsActive);
        
        if (includeChildren)
        {
            AddInclude(e => e.Children);
        }
        
        ApplyOrderBy(e => e.Name);
    }
}

public sealed class {Entity}ByIdSpecification : BaseSpecification<{Entity}>
{
    public {Entity}ByIdSpecification(Guid id, bool includeAll = false)
    {
        AddCriteria(e => e.Id == id);
        
        if (includeAll)
        {
            AddInclude(e => e.Children);
            AddInclude(e => e.Organization);
            AddInclude("Children.SubItems");  // String-based deep include
        }
    }
}

public sealed class Paged{Entities}Specification : BaseSpecification<{Entity}>
{
    public Paged{Entities}Specification(int pageNumber, int pageSize, string? searchTerm = null)
    {
        if (!string.IsNullOrEmpty(searchTerm))
        {
            AddCriteria(e => e.Name.ToLower().Contains(searchTerm.ToLower()));
        }
        else
        {
            AddCriteria(e => e.IsActive);
        }

        ApplyOrderByDescending(e => e.CreatedAt);
        ApplyPaging((pageNumber - 1) * pageSize, pageSize);
    }
}

Template: Specification Evaluator

// src/{name}.infrastructure/Specifications/SpecificationEvaluator.cs
using Microsoft.EntityFrameworkCore;
using {name}.domain.abstractions;

namespace {name}.infrastructure.specifications;

public static class SpecificationEvaluator
{
    public static IQueryable<T> GetQuery<T>(
        IQueryable<T> inputQuery,
        ISpecification<T> specification) where T : class
    {
        var query = inputQuery;

        if (specification.Criteria is not null)
        {
            query = query.Where(specification.Criteria);
        }

        foreach (var include in specification.Includes)
        {
            query = query.Include(include);
        }

        foreach (var includeString in specification.IncludeStrings)
        {
            query = query.Include(includeString);
        }

        if (specification.OrderBy is not null)
        {
            query = query.OrderBy(specification.OrderBy);
        }
        else if (specification.OrderByDescending is not null)
        {
            query = query.OrderByDescending(specification.OrderByDescending);
        }

        if (specification.IsPagingEnabled)
        {
            query = query.Skip(specification.Skip!.Value).Take(specification.Take!.Value);
        }

        return query;
    }
}

Template: Repository Integration

// src/{name}.infrastructure/Repositories/{Entity}Repository.cs
public async Task<IReadOnlyList<{Entity}>> GetAsync(
    ISpecification<{Entity}> specification,
    CancellationToken cancellationToken = default)
{
    return await SpecificationEvaluator
        .GetQuery(_dbContext.Set<{Entity}>(), specification)
        .ToListAsync(cancellationToken);
}

public async Task<{Entity}?> GetFirstOrDefaultAsync(
    ISpecification<{Entity}> specification,
    CancellationToken cancellationToken = default)
{
    return await SpecificationEvaluator
        .GetQuery(_dbContext.Set<{Entity}>(), specification)
        .FirstOrDefaultAsync(cancellationToken);
}

public async Task<int> CountAsync(
    ISpecification<{Entity}> specification,
    CancellationToken cancellationToken = default)
{
    return await SpecificationEvaluator
        .GetQuery(_dbContext.Set<{Entity}>(), specification)
        .CountAsync(cancellationToken);
}

Usage in Handler

public async Task<Result<IReadOnlyList<{Entity}Response>>> Handle(
    Get{Entities}Query request,
    CancellationToken cancellationToken)
{
    var specification = new {Entities}ByOrganizationSpecification(
        request.OrganizationId,
        includeChildren: true);

    var entities = await _{entity}Repository.GetAsync(specification, cancellationToken);

    return entities.Select(e => new {Entity}Response(e)).ToList();
}

Related Skills

  • dotnet-repository-pattern - Repository with specification support
  • dotnet-cqrs-query-generator - Query handlers using specifications
  • dotnet-domain-entity-generator - Entities queried by specifications

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Generates audit trail infrastructure for entities. Implements IAuditable interface, EF Core SaveChanges interceptor, and automatic population of CreatedAt, UpdatedAt, CreatedBy, and UpdatedBy fields.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ronnythedev/dotnet-clean-architecture-skills762026년 7월 14일 업데이트

Scaffolds a complete .NET solution following Clean Architecture principles with proper layer separation (API, Application, Domain, Infrastructure). Creates project structure, dependency injection setup, and cross-cutting concerns configuration.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ronnythedev/dotnet-clean-architecture-skills762026년 7월 14일 업데이트

Generates CQRS Commands with Handlers, Validators, and Request DTOs following Clean Architecture patterns. Commands represent actions that modify state and return Result types for proper error handling.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ronnythedev/dotnet-clean-architecture-skills762026년 7월 14일 업데이트

Generates CQRS Queries with Handlers and Response DTOs for read operations. Uses Dapper for optimized read queries, bypassing the domain model for better performance.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ronnythedev/dotnet-clean-architecture-skills762026년 7월 14일 업데이트

Generates optimized read queries using Dapper. Includes multi-mapping for joins, pagination, dynamic filtering, CTEs, and best practices for high-performance data access.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ronnythedev/dotnet-clean-architecture-skills762026년 7월 14일 업데이트

Generates Domain Entities following DDD principles with factory methods, private setters, domain events, and proper encapsulation. Supports aggregate roots, child entities, and value objects.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ronnythedev/dotnet-clean-architecture-skills762026년 7월 14일 업데이트

ronnythedev의 스킬 모두 보기

이 스킬의 문제 신고