RoomSharp.DependencyInjection 0.5.5

dotnet add package RoomSharp.DependencyInjection --version 0.5.5
                    
NuGet\Install-Package RoomSharp.DependencyInjection -Version 0.5.5
                    
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="RoomSharp.DependencyInjection" Version="0.5.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RoomSharp.DependencyInjection" Version="0.5.5" />
                    
Directory.Packages.props
<PackageReference Include="RoomSharp.DependencyInjection" />
                    
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 RoomSharp.DependencyInjection --version 0.5.5
                    
#r "nuget: RoomSharp.DependencyInjection, 0.5.5"
                    
#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 RoomSharp.DependencyInjection@0.5.5
                    
#: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=RoomSharp.DependencyInjection&version=0.5.5
                    
Install as a Cake Addin
#tool nuget:?package=RoomSharp.DependencyInjection&version=0.5.5
                    
Install as a Cake Tool

RoomSharp.DependencyInjection

Dependency Injection extensions for integrating RoomSharp databases with IServiceCollection using familiar ASP.NET Core patterns.

Installation

dotnet add package RoomSharp.DependencyInjection

Quick Start

var builder = WebApplication.CreateBuilder(args);

// Register database
builder.Services.AddRoomSharpDatabase<AppDatabase>(context =>
{
    context.UseSqlite("app.db");
    context.Builder
        .SetVersion(1)
        .AddMigrations(new InitialMigration());
});

// Register DAOs — manually
builder.Services.AddRoomSharpDao<AppDatabase, ITodoDao>(db => db.TodoDao);

// Or auto-register all DAOs at once
builder.Services.AddRoomSharpDaos<AppDatabase>();

Provider Shortcuts

Configure your database provider directly from the builder context:

// SQLite
context.UseSqlite("app.db");
context.UseSqliteInMemory();
context.UseSqliteWithConnectionString("Data Source=app.db;Mode=ReadWriteCreate");

// SQL Server (requires RoomSharp.SqlServer)
context.UseSqlServer("Server=.;Database=MyApp;Trusted_Connection=True;");

// PostgreSQL (requires RoomSharp.PostgreSql)
context.UsePostgres("Host=localhost;Database=myapp;Username=user;Password=pass;");

// MySQL/MariaDB (requires RoomSharp.MySql)
context.UseMySql("Server=localhost;Database=myapp;User=root;Password=pass;");

// Custom provider resolved from DI
context.UseProvider<MyCustomProvider>("connection-string");

Encryption & Audit Setup

Configure [Encrypted] and [Auditable] features directly from the DI builder:

builder.Services.AddRoomSharpDatabase<AppDatabase>(context =>
{
    context.UseSqlite("app.db");

    // Encryption — pass an instance
    context.SetEncryptionProvider(new AesEncryptionProvider(key));

    // Or resolve IEncryptionProvider from the DI container
    context.SetEncryptionProviderFromServices();

    // Audit — pass an instance
    context.SetAuditContext(new MyAuditContext(userId));

    // Or resolve IAuditContext from the DI container
    context.SetAuditContextFromServices();
});

Service Lifetime

Control the database and DAO lifetimes:

// Singleton (default)
builder.Services.AddRoomSharpDatabase<AppDatabase>(
    ctx => ctx.UseSqlite("app.db"));

// Scoped — new instance per request
builder.Services.AddRoomSharpDatabase<AppDatabase>(
    ctx => ctx.UseSqlite("app.db"),
    ServiceLifetime.Scoped);

// Shorthand for scoped
builder.Services.AddRoomSharpScopedDatabase<AppDatabase>(
    ctx => ctx.UseSqlite("app.db"));

Captive Dependency Protection: RoomSharp validates lifetime compatibility. A Singleton DAO with a Scoped database will throw InvalidOperationException at registration time.

Database Factory

For background services, Blazor Server, or manual lifecycle control:

builder.Services.AddRoomSharpDatabaseFactory<AppDatabase>(ctx =>
    ctx.UseSqlite("app.db"));

// Usage in a background service
public class MyWorker : BackgroundService
{
    private readonly IRoomDatabaseFactory<AppDatabase> _factory;

    public MyWorker(IRoomDatabaseFactory<AppDatabase> factory)
        => _factory = factory;

    protected override async Task ExecuteAsync(CancellationToken token)
    {
        using var db = _factory.Create();
        var todos = await db.TodoDao.GetAllAsync();
    }
}

Each Create() / CreateAsync() call creates a fresh database instance and its own DI scope. Any scoped services resolved through the builder context, such as IAuditContext or IEncryptionProvider, are disposed together with the database instance.

Pooled Database Registration

Use pooled registration when you want scoped resolution plus an explicit cap on concurrent parallel database instances:

builder.Services.AddRoomSharpPooledDatabase<AppDatabase>(
    ctx => ctx.UseSqlite("app.db"),
    maxPoolSize: 8);

Notes:

  • maxPoolSize is wired to RoomSharp's parallel session/connection limiter.
  • When the limit is reached, additional OpenSessionAsync() calls wait until capacity is available.
  • This is intended for ConcurrencyMode.Parallel workloads where you want bounded connection fan-out.

Configuration-Based Registration

Bind connection strings from IConfiguration:

builder.Services.AddRoomSharpDatabase<AppDatabase>(
    configuration,
    connectionStringName: "Default",
    providerFactory: sp => new SqlServerProvider(),
    configure: b => b.SetVersion(2));

Health Checks

Register a health check that verifies actual database connectivity via SELECT 1:

builder.Services.AddHealthChecks()
    .AddRoomSharpDatabase<AppDatabase>();

// With custom name and tags
builder.Services.AddHealthChecks()
    .AddRoomSharpDatabase<AppDatabase>(
        name: "app-db",
        tags: new[] { "db", "critical" });

The health check creates its own DI scope before resolving the database. That keeps scoped RoomSharp registrations valid and avoids resolving request-scoped databases from the root provider.

Keyed Services (.NET 8+)

Register multiple database instances with different keys:

builder.Services.AddKeyedRoomSharpDatabase<AppDatabase>("primary",
    ctx => ctx.UseSqlite("primary.db"));

builder.Services.AddKeyedRoomSharpDatabase<AppDatabase>("secondary",
    ctx => ctx.UsePostgres(secondaryConnStr));

// Resolve
var db = sp.GetRequiredKeyedService<AppDatabase>("primary");

Keyed DAO registrations use the same lifetime validation as regular DAO registrations. A keyed singleton DAO cannot capture a keyed scoped database.

API Reference

Service Collection Extensions

Method Description
AddRoomSharpDatabase<T>(configure, lifetime?) Register database with builder callback
AddRoomSharpDatabase<T>(context, lifetime?) Register with access to IServiceProvider
AddRoomSharpDatabase<T>(config, connName, ...) Bind from IConfiguration
AddRoomSharpScopedDatabase<T>(configure) Shorthand for scoped registration
AddRoomSharpDatabaseFactory<T>(configure) Register factory for manual lifecycle with per-database DI scope ownership
AddRoomSharpPooledDatabase<T>(configure, maxPoolSize?) Register scoped databases backed by a bounded parallel session/connection limit
AddRoomSharpDao<TDb, TDao>(factory, lifetime?) Register a single DAO with factory + captive dependency validation
AddRoomSharpDaos<TDb>(lifetime?) Auto-discover and register all abstract DAO properties from the database
AddKeyedRoomSharpDatabase<T>(key, configure, lifetime?) Register keyed database (.NET 8+)
AddKeyedRoomSharpDao<TDb, TDao>(key, dbKey, factory, lifetime?) Register keyed DAO (.NET 8+) with captive dependency validation

Builder Context Methods

Method Description
UseSqlite(path) Configure SQLite with file path
UseSqliteInMemory() Configure SQLite in-memory
UseSqliteWithConnectionString(connStr) Configure SQLite with full connection string
UseSqlServer(connStr) Configure SQL Server
UsePostgres(connStr) Configure PostgreSQL
UseMySql(connStr) Configure MySQL/MariaDB
UseProvider<T>(connStr) Resolve custom provider from DI
UseProvider(provider, connStr) Use externally constructed provider
SetEncryptionProvider(provider) Set encryption for [Encrypted] properties
SetEncryptionProviderFromServices() Resolve IEncryptionProvider from DI
SetAuditContext(context) Set audit context for [Auditable] entities
SetAuditContextFromServices() Resolve IAuditContext from DI

Health Check Extensions

Method Description
AddRoomSharpDatabase<T>(name?, failureStatus?, tags?) Register health check with real DB ping
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 is compatible.  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 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
0.5.5 5 5/10/2026
0.5.4 94 5/1/2026
0.5.3 86 4/30/2026
0.5.2 100 4/28/2026
0.5.1 92 4/27/2026
0.5.0 103 4/20/2026
0.4.7 122 1/15/2026
0.4.6 117 1/11/2026
0.4.5 117 1/3/2026
0.4.4 135 12/26/2025
0.4.3 265 12/19/2025
0.3.2 224 12/3/2025

v0.5.2

           Highlights:
           - AddRoomSharpDaos<TDatabase>() auto-registers abstract DAO properties from the RoomDatabase type.
           - Builder context now supports SetEncryptionProvider(...) / SetEncryptionProviderFromServices(...) for [Encrypted] features.
           - Builder context now supports SetAuditContext(...) / SetAuditContextFromServices(...) for [Auditable] user tracking.
           - Keyed RoomSharp database/DAO registration support remains available for multi-database applications.

           Improvements:
           - Health checks now perform a real connectivity probe instead of only resolving the DI instance.
           - Database factories now create an owned DI scope per database instance so scoped audit/encryption services are disposed correctly.
           - AddRoomSharpPooledDatabase(...) now respects maxPoolSize, and keyed DAO registration now enforces captive dependency validation.
           - DI integration is aligned with RoomSharp 0.5.2 generated lifecycle features, including encryption and audit support.
           - Registration/validation flow is cleaner and more reliable for production IServiceCollection setups.