Lib.Db 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Lib.Db --version 1.0.0
                    
NuGet\Install-Package Lib.Db -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Lib.Db" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Lib.Db" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Lib.Db" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Lib.Db --version 1.0.0
                    
#r "nuget: Lib.Db, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Lib.Db@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Lib.Db&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Lib.Db&version=1.0.0
                    
Install as a Cake Tool

Lib.Db (v2.0 'Quantum Leap')

Extreme Performance Data Access Library for .NET 10+

.NET NuGet AOT Ready License Zero Allocation


⚡ 핵심 가치 (Core Values)

Lib.Db는 현대적인 .NET 애플리케이션을 위한 성능 집약적 SQL Server 데이터 액세스 라이브러리입니다.

  1. Zero-Allocation: ArrayPool, Span<T>, SqlInterpolatedStringHandler를 통해 힙 메모리 할당을 최소화합니다.
  2. AOT-First: **Dual-Layer Configuration Strategy(Shadow DTO)**를 적용하여 바인딩 경고 없이 Native AOT를 완벽 지원합니다.
  3. Resilience-by-Design: Polly v8 파이프라인과 카오스 엔지니어링 도구가 내장되어 있어 안정적인 프로덕션 운영이 가능합니다.
  4. Process Coordination: 공유 메모리(MMF) 기반의 멀티 프로세스 캐시 동기화 및 자동 리더 선출을 지원합니다.

📊 성능 벤치마크 (Performance)

상세 벤치마크 데이터는 향후 docs/10_performance_benchmarks.md에서 제공 예정

시나리오 Dapper EF Core Lib.Db 개선율
단순 조회 (1,000건) 12.3ms 18.7ms 8.9ms +28%
Bulk Insert (100K건) N/A 45s 4.2s 10배↑
메모리 사용량 1.23MB 2.45MB 0.85MB -31%
GC Gen0 수집 150회 320회 32회 -78%

위 수치는 예시이며, 실제 측정 결과는 환경에 따라 다를 수 있습니다.


🔧 호환성 (Compatibility)

Platform .NET Version SQL Server Status
Windows .NET 10 SQL Server 2016+ ✅ 지원
Linux .NET 10 SQL Server 2017+ ✅ 지원
macOS .NET 10 SQL Server 2017+ ✅ 지원
Docker .NET 10 Azure SQL ✅ 지원
Native AOT .NET 10 모든 버전 ✅ 완벽 지원

NuGet Packages:

  • Lib.Db - 런타임 라이브러리 (v2.0.0)
  • Lib.Db.TvpGen - Source Generator (v2.0.0)
    • Table-Valued Parameters (TVP) 자동 생성
    • DbDataReader → DTO 고성능 매핑 (Track 5 알고리즘)
    • Native AOT 완벽 지원 (리플렉션 제로)
    • 📘 상세 가이드 →

🏎️ 라이브러리 비교 (Comparison)

기능 Dapper EF Core ADO.NET Lib.Db
Reflection ✅ 사용 ✅ 사용 ❌ (Source Gen)
Native AOT ⚠️ 제한적 ✅ 완벽 지원
Bulk Ops ⚠️ 제한 ✅ 최적화 지원
Zero-Alloc ⚠️ 부분 ✅ 핵심 설계
Process IPC ✅ MMF 기반
Resilience ✅ Polly v8 내장

🚀 5분 시작 가이드 (Quick Start)

1. 서비스 등록 (권장)

WebApplication뿐만 아니라 콘솔/워커 서비스에서도 사용 가능한 범용 호스트(Generic Host) 패턴입니다.

// Program.cs
using Microsoft.Extensions.Hosting;
using Lib.Db.Extensions;

var builder = Host.CreateApplicationBuilder(args);

// 1. 범용 호스트 빌더 생성 (appsettings.json 자동 로드)
// .NET 10 호스트 패턴 권장
builder.Services.AddLibDb(builder.Configuration);

var host = builder.Build();

// 2. 애플리케이션 실행
// 스키마 워밍업은 SchemaWarmupService에서 자동으로 수행됩니다.
await host.RunAsync();

Tip: 별도의 IConfiguration 로드 없이 builder.Configuration을 바로 전달하면 됩니다.

2. appsettings.json 구성

{
  "LibDb": {
    "ConnectionStrings": {
      "Main": "Server=localhost;Database=LibDb;Trusted_Connection=True;TrustServerCertificate=True;"
    },
    // 실행 옵션
    "Execution": {
      "DefaultCommandTimeoutSeconds": 30,
      "StrictRequiredParameterCheck": true  // [중요] C# 14 Validation으로 잘못된 값 즉시 예외 발생
    },
    // 캐싱 및 공유 메모리
    "Caching": {
      "EnableSharedMemoryCache": true,
      "MaxCacheSize": 2048
    },
    // 장애 주입 (테스트용)
    "Chaos": {
      "Enabled": false,
      "ExceptionRate": 0.05
    }
  }
}

3. Repository 패턴 사용 (.NET 10 Primary Constructors)

using Lib.Db.Contracts;

// C# 14 Primary Constructor
public class UserRepository(IDbContext db)
{
    // Record 타입 (Entity)
    public record User(int Id, string Name, string Email);

    public async Task<User?> GetUserAsync(int id)
    {
        // String Interpolation Handler로 SQL Injection 방지 및 Zero-Allocation
        return await db.Default
            .Sql($"SELECT * FROM Users WHERE Id = {id}")
            .QuerySingleAsync<User>();
    }
    
    public async Task<int> RegisterUserAsync(string name, string email)
    {
        return await db.Default
            .Sql($"INSERT INTO Users (Name, Email) VALUES ({name}, {email}); SELECT SCOPE_IDENTITY();")
            .ExecuteScalarAsync<int>();
    }
}

📖 기술 백서 (Technical Whitepapers)

라이브러리의 각 주제에 대한 심층적인 기술 문서는 아래 모듈에서 확인할 수 있습니다.

핵심 가이드

  • 01. 아키텍처 개요
    • 시스템 구조, 핵심/보호 레이어 분리 원칙, 형태-의미 동형성, 주요 컴포넌트 목록.
  • 02. 설치 및 구성
    • NuGet 설치, DI 컨테이너 등록, appsettings.json 전체 옵션 가이드 (176개 설정 항목).
  • 03. Fluent API 레퍼런스
    • DbRequestBuilder 사용법, 파라미터 바인딩, 비동기 쿼리 패턴 (656줄 완전 레퍼런스).

고급 주제

운영 가이드

API 및 마이그레이션

Source Generator 📦

  • Lib.Db.TvpGen README 🔥
    • TVP 자동 생성: [TvpRow] 어노테이션으로 SQL Server TVP 매핑 (18개 타입 지원)
    • 결과 매핑: [DbResult] 어노테이션으로 DbDataReader → DTO 고성능 매핑
    • DB-First: libdb.schema.json으로 DTO 자동 생성
    • 완전한 타입 레퍼런스: JSON Schema 타입 매핑표 (Bit, Int, BigInt, DateTime2, Guid 등)
    • Track 5 알고리즘: Small(≤12) Span.SequenceEqual, Large(>12) FNV-1a 해시

🌟 주요 기능

  • 3-Tier Connection Pooling - Default/Admin/Custom 연결 관리
  • 🔄 Automatic Retry & Circuit Breaker - Polly v8 기반 자동 복원
  • 💾 L1+L2 HybridCache - 프로세스 내/간 캐시 자동 동기화
  • 🚀 Bulk Operations - BulkInsert/Update/Delete + Pipeline 지원
  • 📊 Resumable Query - 네트워크 단절 시 자동 재개
  • 🔐 SQL Injection 자동 방지 - SqlInterpolatedStringHandler
  • 📈 OpenTelemetry 통합 - 성능 메트릭 자동 수집
  • 🧪 Chaos Engineering - 개발 환경 장애 시뮬레이션

📦 샘플 프로젝트

샘플 프로젝트는 별도 리포지토리에서 제공 예정

  • Lib.Db.Samples.WebApi - ASP.NET Core Web API 예제
  • Lib.Db.Samples.Worker - Background Worker 예제
  • Lib.Db.Samples.Benchmarks - BenchmarkDotNet 성능 측정

🤝 기여 및 라이선스

  • License: MIT License
  • Contributions: Pull Requests를 환영합니다!
  • Issues: 버그 리포트 및 기능 요청은 GitHub Issues로

<p align="center"> Developed by <strong>김재석</strong> </p>

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.2.0 40 4/16/2026
2.1.0 92 4/6/2026
1.1.1 112 1/9/2026
1.1.0 107 1/9/2026
1.0.0 108 12/30/2025