-1

I wanted to check in program.cs "force" after "builde", when the application is loaded, if it is local (127.0.0.1), it will use the local database (LocalConnection), and if it is a server, it will use the server database(DefaultConnection).

(It is not useful for me after app and only after build needed)

var builder = WebApplication.CreateBuilder(args);
var connectionString="";

bool isLocal= ...?<<<<<<<<<<<<?

if (isLocal)
{
    var connectionString0 = builder.Configuration.GetConnectionString("LocalConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
    connectionString = connectionString0;
}
else
{
    var connectionString0 = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
    connectionString = connectionString0;
}
...
var app = builder.Build();
//It is not useful for me after app.
...

pls befor answer that, check your solution in blazor web app 8.0 only, tnks.

not working:

Using multiple connection strings

2
  • Could specify what does "islocal" means? Does it mean visit the website on the server machine or on another client machine? Commented Mar 19, 2024 at 6:50
  • If I'm reading this correctly. there's no such thing as Local and Remote at startup. Every server has a 127.0.0.1 address. The Remote/Local context only applies to a HttpRequest from a browser when the application is running. Commented Mar 19, 2024 at 8:10

1 Answer 1

0

If your want different ConnectionString depending on the some information in the request (such as "hostname" to determine if the request from local) , you could register two DbContext( such as "MyContext1" and "MyContext2") with different ConnectionString. Then Create an Interface for them such as "IMyContext", the following code will let the IMyContext resolve different service depending on request.

    public class MyContext1 :DbContext, IMyContext
    {
       ...
    }
    public class MyContext2 :DbContext, IMyContext
    {
       ...
    }
builder.Services.AddHttpContextAccessor();

builder.Services.AddDbContext<MyContext1>(options...);
builder.Services.AddDbContext<MyContext2>(options...);
builder.Services.AddScoped<IMyContext>(provider =>
{
    var acceessor = provider.GetService<IHttpContextAccessor>();
    string hostname = acceessor.HttpContext.Request.Headers["Host"][0];
    if (hostname.Contains("localhost"))
    {
        return provider.GetService<MyContext1>();
    }
    else
    {
        return provider.GetService<MyContext2>();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.