Luis Abreu
Luis Abreu

Reputation: 4570

IdentityServer4: Reuse SqlConnection when calling the AddConfigurationStore extension method

In my case, I have several EF contexts that share the same database (ie, all the tables are on the same db) and I'd like to share the same SqlConnection amongst all contexts so that I can apply several changes inside the same transaction.

In order to achieve this, I've started by registering the SqlConnection with the following code:

services.AddScoped(sp => new SqlConnection(Configuration.GetConnectionString("DefaultConnection")));

After doing this, I've change one of the EF contexts so that it reuses the same connection:

services.AddDbContext<ApplicationDbContext>((provider, options) =>

options.UseSqlServer(provider.GetRequiredService()));

I need to do something similar when registering the configuration and operational store. Unlike the EF extension method, there isn't an overload which lets me pass an Action that references the options builder and the service provider:

services.AddIdentityServer()
            .AddConfigurationStore(options =>
            {
                // HERE: no serviceprovider, how can I get the SqlConnection object???
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                        sql => sql.MigrationsAssembly(migrationsAssembly));
            })

builder.UseSqlServer does have an overload which lets me pass the connection, but how can I resolve the SqlConnection at runtime so that the same connection is shared across all contexts?

Thanks,

Luis

Upvotes: 2

Views: 310

Answers (1)

Luis Abreu
Luis Abreu

Reputation: 4570

Answered by the man himself :)

Instead of using the CondigureDbContext property, you should use the ResolveDbContextOptions:

.AddConfigurationStore(options => {
     options.ResolveDbContextOptions = (provider, builder) => 
     builder.UseSqlServer(provider.GetRequiredService<Foo>().FooValue);
})

Upvotes: 1

Related Questions