Skip to content

Instantly share code, notes, and snippets.

@kijanawoodard
Last active June 8, 2025 00:34
Show Gist options
  • Save kijanawoodard/6822bba8dfa40d4188ee4ee5d0c94145 to your computer and use it in GitHub Desktop.
Save kijanawoodard/6822bba8dfa40d4188ee4ee5d0c94145 to your computer and use it in GitHub Desktop.
dotnet aspire AddSqlServerDbContextFactory
public static class AspireExtensions
{
public static WebApplicationBuilder AddSqlServerDbContextFactory<TContext>(this WebApplicationBuilder builder, string connectionName, ServiceLifetime serviceLifetime = ServiceLifetime.Singleton)
where TContext : DbContext
{
var connectionString = builder.Configuration.GetConnectionString(connectionName);
builder.Services.AddDbContextFactory<TContext>(options => options.UseSqlServer(connectionString), serviceLifetime);
builder.EnrichSqlServerDbContext<TContext>();
return builder;
}
}
// call it like this
builder.AddSqlServerDbContextFactory<DatabaseContext>("sqldb", ServiceLifetime.Scoped);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment