About Connection Strings - lobodava/artisan-orm GitHub Wiki

The RepositoryBase constructor takes a connection string directly:

public RepositoryBase(string connectionString);
public RepositoryBase(SqlTransaction? transaction, string connectionString);

It creates a SqlConnection (left closed) and stores it on the public Connection property. The connection is opened on demand by individual Read* / Execute* methods and closed afterwards if it was opened by them.

Earlier versions of Artisan.Orm read the connection string from Web.config / App.config automatically by name, with optional per-machine and per-build-configuration overrides. From version 4.0 that machinery has been removed: pick whichever .NET configuration source you like and pass the resolved connection string to the constructor.

Modern .NET — appsettings.json + DI

// appsettings.json
{
  "ConnectionStrings": {
    "DatabaseConnection": "Data Source=.\\SQLEXPRESS;Initial Catalog=Artisan;Integrated Security=True;TrustServerCertificate=True;"
  }
}

Register repositories as Scoped so each HTTP request gets its own instance with its own connection and transaction state:

// Program.cs
var builder = WebApplication.CreateBuilder(args);

var connStr = builder.Configuration.GetConnectionString("DatabaseConnection")!;

builder.Services.AddScoped(_ => new UserRepository(connStr));
builder.Services.AddScoped(_ => new RecordRepository(connStr));

See Using Artisan.Orm in ASP.NET Core for the full lifetime / DI story (background services, scope sharing, why not Singleton / Transient).

Console / scripts / one-off code

When there is no DI container around, just using the repository:

using var repo = new UserRepository(connectionString);
var user = repo.GetUserById(1);

Connection pool

Make sure your production connection string keeps the default Pooling=True. Setting Pooling=False (sometimes useful in tests to avoid masking connection-leak bugs) disables ADO.NET's connection pool, so every using var repo = ... will perform a full TDS handshake instead of borrowing a pooled connection.

Per-environment connection strings

Use the standard ASP.NET Core configuration layering — appsettings.Development.json, appsettings.Production.json, environment variables, user secrets — instead of putting machine names into config keys.

# Pick the active environment via ASPNETCORE_ENVIRONMENT
set ASPNETCORE_ENVIRONMENT=Development & dotnet run

# Or store the developer connection string in user secrets
dotnet user-secrets set "ConnectionStrings:DatabaseConnection" "Data Source=..."

The IConfiguration.GetConnectionString("DatabaseConnection") call automatically resolves the layered value at startup.

Legacy .NET Framework

If you are still on .NET Framework with App.config / Web.config, read the connection string the standard way and pass it in:

var connStr = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
var repo = new UserRepository(connStr);

See also: