Skip to content

Instantly share code, notes, and snippets.

@JimBobSquarePants
Created February 28, 2020 04:04
Show Gist options
  • Save JimBobSquarePants/da8f2a82e88d75bb7e465b540f23f8be to your computer and use it in GitHub Desktop.
Save JimBobSquarePants/da8f2a82e88d75bb7e465b540f23f8be to your computer and use it in GitHub Desktop.
Registering a LocalDb instance via MS DI.
static void RegisterDbContext<TContext>(IServiceCollection services)
where TContext : DbContext
{
services.AddSingleton<SqlInstance<TContext>>(p => new SqlInstance<TContext>(builder => (TContext)ActivatorUtilities.CreateInstance<TContext>(p, builder.Options)));
services.AddScoped<SqlDatabase<TContext>>(p =>
{
SqlInstance<TContext> sqlInstance = p.GetRequiredService<SqlInstance<TContext>>();
// Safe excecution of async via dedicated factory and unwrapping.
return RunSync(() => sqlInstance.Build(typeof(TContext).Name));
});
services.AddScoped<TContext>(p =>
{
SqlDatabase<TContext> database = p.GetRequiredService<SqlDatabase<TContext>>();
return database.NewDbContext();
});
}
@SimonCropp
Copy link

sorry for the delay

SqlInstance maps to a sql server instance. it should be called once per appdomain. so eg in a module init, in a static ctor of a test base class, in a testfixture global [startup]. i find the static ctor of a test base class to be the most common since u only pay the startup cost on test that use the db. so if u run a non-db test in isolation, the db interaction wont inpact it.

it is a unique db per test method. they are not cleaned up, but left running after a test so u can debug the db instance if necessary. u can opt in to delete the db https://github.com/SimonCropp/LocalDb/blob/master/src/LocalDb/SqlDatabase.cs#L55

Database files older than a day will be purged from the data directory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment