Home > OS >  How to select configuration section based on route value
How to select configuration section based on route value

Time:07-08

I have an ASP.NET Core 6 MVC website. It also uses Entity Framework Core. I want to configure my website so that the first part of the route defines which configuration section to use.

My appsettings.json file will have multiple sections, all with same structure, just some settings value is changed. It will look something like this:

"standardConfigs": {
    "ConnectionString": "Server=MyStandardServer;Database=MyStandardDB;user id=*****;password=*****;MultipleActiveResultSets=true",  
    "AdditionalSettings": "SomeValue",  
},
"upgradedConfigs": {
    "ConnectionString": "Server=MyUpgradedServer;Database=MyUpgradedDB;user id=*****;password=*****;MultipleActiveResultSets=true",  
    "AdditionalSettings": "SomeOtherValue",  
},

In StartUp.cs, Entity Framework Core is configured to use a connection string from configuration. If the user hits the url http://example.com/standard/somecontroller/someaction/, I want to get the first part of the route ('standard' in this case) and use it to select the configuration section ('standardConfigs') from where the connection string will come.

It should look like this:

var configSectionName = GetFirstPartOfRoute(); // How to do this?
var dbConfig = Configuration
        .GetSection(configSectionName   "Configs")
        .Get<MyConfiguration>();
services.AddDbContext<URMSContext>(options =>
                options.UseLazyLoadingProxies().UseSqlServer(dbConfig.ConnectionString)
                    );

How to configure this in my website? This is my general idea how to make it work. If you have a better idea to select configuration based on route value feel free to share.

CodePudding user response:

Following the documentation, you can subclass DbContext and override OnConfiguring method.

You have to inject IHttpContextAccessor as well in order to access the route in the DbContext.

Make sure to add Your new DbCotnext as scoped.

CodePudding user response:

do this in program.cs

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddDbContext<URMSContext>((serviceProvider, dbContextBuilder) =>
{
    var httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
    
    // extract configsection from this path
    var configSectionName = httpContextAccessor.HttpContext.Request.Path; 
    
    var dbConfig = Configuration
        .GetSection(configSectionName   "Configs")
        .Get<MyConfiguration>();
    dbContextBuilder.UseSqlServer(dbConfig.ConnectionString);
});
  • Related