-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Closed
Closed
Copy link
Milestone
Description
When creating integration tests for a project with ASP.NET Core, you probably want to modify the already registered DbContext with your options for testing. So for example, you may want to change the connection string or enable sensitve data logging.
To do so you you cannot just call again AddDbContext with your new options, as they are registered with TryAdd. You have to mess with serviceDescriptors and remove the options for that DbContext (once you know that removing the descriptor for DbContext is not what you need).
Code sample:
public static IServiceCollection RemoveDbContextOptions<TContext>(this IServiceCollection services) where TContext : DbContext
{
var serviceDescriptor = services.Single(d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
services.Remove(serviceDescriptor);
return services;
}
services.RemoveDbContextOptions<AppDbContext>();
services.AddDbContext<AppDbContext>(options => options.EnableSensitiveDataLogging());
An extension method like the previous one could help in this case for removing DbContexts or its options when needed.