Skip to content

Add ServiceCollection extension method for removing a DbContext or its options #33571

@michaeltg17

Description

@michaeltg17

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions