DbDapperFactory 0.1.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package DbDapperFactory --version 0.1.2
                    
NuGet\Install-Package DbDapperFactory -Version 0.1.2
                    
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="DbDapperFactory" Version="0.1.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DbDapperFactory" Version="0.1.2" />
                    
Directory.Packages.props
<PackageReference Include="DbDapperFactory" />
                    
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 DbDapperFactory --version 0.1.2
                    
#r "nuget: DbDapperFactory, 0.1.2"
                    
#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 DbDapperFactory@0.1.2
                    
#: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=DbDapperFactory&version=0.1.2
                    
Install as a Cake Addin
#tool nuget:?package=DbDapperFactory&version=0.1.2
                    
Install as a Cake Tool

DbDapperFactory

Factory + extensiones de DI para crear DbConnection nombradas y usarlas con Dapper.

⚠️ MIGRACIÓN: Los paquetes DbDapperFactory.Core, DbDapperFactory.SqlServer, DbDapperFactory.Postgres, DbDapperFactory.MySql, DbDapperFactory.Sqlite y DbDapperFactory.Oracle han sido consolidados en un único paquete DbDapperFactory. Por favor, migra a este paquete único para recibir actualizaciones futuras.

¿Qué es DbDapperFactory?

DbDapperFactory es una librería que facilita la integración de múltiples bases de datos en aplicaciones .NET usando Dapper como ORM ligero. Proporciona:

  • 🏭 Factory de conexiones nombradas: Define múltiples conexiones a diferentes bases de datos y accede a ellas por nombre.
  • 📦 Inyección de dependencias (DI): Integración nativa con Microsoft.Extensions.DependencyInjection.
  • 🗄️ Soporte multi-proveedor integrado: SqlServer, PostgreSQL, MySQL, SQLite, Oracle - todo en un solo paquete.
  • 🔌 Simple y ligero: Minimal overhead, máximo control sobre las conexiones.

Instalación

Instala el único paquete DbDapperFactory que incluye soporte para todos los proveedores de bases de datos:

dotnet add package DbDapperFactory

O desde NuGet Package Manager.

Uso Básico (DI + conexiones nombradas)

1. Configura en el startup

using DbDapperFactory;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Registra la factory y define tus conexiones
builder.Services
    .AddDapperConnectionFactory()
    .AddSqlServer("Main", configuration.GetConnectionString("Main")!)
    .AddPostgres("Reporting", configuration.GetConnectionString("Reporting")!);

var app = builder.Build();

2. Inyecta y usa en tus servicios

using DbDapperFactory;
using Dapper;

public sealed class UsersRepository
{
    private readonly IDapperConnectionFactory _connections;

    public UsersRepository(IDapperConnectionFactory connections)
        => _connections = connections;

    // Obtener usuario por ID
    public async Task<User?> GetByIdAsync(Guid id)
    {
        using var conn = _connections.CreateConnection("Main");
        return await conn.QuerySingleOrDefaultAsync<User>(
            "select * from users where id = @id",
            new { id });
    }

    // Listar usuarios
    public async Task<List<User>> GetAllAsync()
    {
        using var conn = _connections.CreateConnection("Main");
        var users = await conn.QueryAsync<User>("select * from users");
        return users.ToList();
    }

    // Crear usuario
    public async Task<int> CreateAsync(User user)
    {
        using var conn = _connections.CreateConnection("Main");
        return await conn.ExecuteAsync(
            "insert into users (id, name, email) values (@id, @name, @email)",
            user);
    }
}

// Modelo
public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

Ejemplos Avanzados

Múltiples bases de datos

Con un único paquete DbDapperFactory, puedes usar todos los proveedores simultáneamente:

// Configuración - todo en un solo paquete
builder.Services
    .AddDapperConnectionFactory()
    .AddSqlServer("Main", "Server=localhost;Database=MyApp;...")
    .AddPostgres("Analytics", "Host=localhost;Database=Analytics;...")
    .AddMySql("Legacy", "Server=localhost;Database=OldApp;...");

// Uso
public class ReportingService
{
    private readonly IDapperConnectionFactory _connections;

    public ReportingService(IDapperConnectionFactory connections)
        => _connections = connections;

    public async Task<List<DailySales>> GetSalesFromAnalyticsAsync()
    {
        using var conn = _connections.CreateConnection("Analytics");
        return (await conn.QueryAsync<DailySales>(
            "select * from daily_sales where date >= @startDate",
            new { startDate = DateTime.Now.AddDays(-30) })).ToList();
    }

    public async Task<List<LegacyUser>> GetUsersFromLegacyAsync()
    {
        using var conn = _connections.CreateConnection("Legacy");
        return (await conn.QueryAsync<LegacyUser>(
            "select * from users")).ToList();
    }
}

Configuración personalizada por proveedor

// SQL Server con opciones
builder.Services
    .AddDapperConnectionFactory()
    .AddSqlServer(
        "Main",
        "Server=localhost;Database=MyApp;...",
        configure: conn =>
        {
            conn.ConnectionTimeout = 30;
        });

// PostgreSQL
builder.Services.AddPostgres(
    "Reporting",
    "Host=localhost;Database=Analytics;...");

// MySQL
builder.Services.AddMySql(
    "Users",
    "Server=localhost;Database=UsersDb;...");

// SQLite
builder.Services.AddSqlite(
    "Cache",
    "Data Source=cache.db;");

// Oracle
builder.Services.AddOracle(
    "Legacy",
    "Data Source=OracleDB;User Id=user;Password=pass;");

Notas Importantes

  • ✅ La factory no abre la conexión automáticamente. Tú controlas cuándo llamar a Open()/OpenAsync().
  • ✅ Cada llamada a CreateConnection(name) crea una instancia nueva de conexión.
  • ✅ Usa using para asegurar que la conexión se cierre y disponga correctamente.
  • ✅ Compatible con Dapper para queries, inserts, updates, deletes y procedimientos almacenados.

Características

Característica Detalles
Un solo paquete Todo incluido - SqlServer, PostgreSQL, MySQL, SQLite, Oracle
Inyección de Dependencias Integrada con IServiceCollection
Conexiones Nombradas Define múltiples conexiones y accede por nombre
Async/Await Compatible con operaciones asincrónicas
Dapper Integration Funciona perfectamente con Dapper
Lightweight Minimal, sin dependencias pesadas

Proveedores Soportados

SQL Server - AddSqlServer()
PostgreSQL - AddPostgres()
MySQL - AddMySql()
SQLite - AddSqlite()
Oracle - AddOracle()

Licencia

Este proyecto está bajo licencia MIT.

Migración desde versiones antiguas

Si estabas usando los paquetes individuales (DbDapperFactory.Core, DbDapperFactory.SqlServer, etc.), sigue estos pasos para migrar:

Paso 1: Desinstala los paquetes antiguos

dotnet remove package DbDapperFactory.Core
dotnet remove package DbDapperFactory.SqlServer
dotnet remove package DbDapperFactory.Postgres
dotnet remove package DbDapperFactory.MySql
dotnet remove package DbDapperFactory.Sqlite
dotnet remove package DbDapperFactory.Oracle

Paso 2: Instala el paquete único

dotnet add package DbDapperFactory

Paso 3: Sin cambios de código necesarios

El código existente seguirá funcionando sin modificaciones. Los namespaces y las APIs son idénticas:

using DbDapperFactory; // ✅ Sigue siendo igual

builder.Services
    .AddDapperConnectionFactory()
    .AddSqlServer("Main", connectionString)
    .AddPostgres("Reporting", connectionString);

Por qué consolidamos

  • Más simple: Un solo paquete en lugar de 6
  • Versioning único: Todas las funcionalidades se versionan juntas
  • Mantenimiento: Código más fácil de mantener
  • Actualizaciones: Recibe todas las mejoras en un solo paquete
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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
0.1.3 123 3/17/2026
0.1.2 106 2/19/2026
0.1.1 98 2/19/2026
0.1.0 103 2/18/2026