我想在“builde”之后检查program.cs“force”,当应用程序加载时,如果是本地(127.0.0.1),它将使用本地数据库(LocalConnection),如果是服务器,它将使用服务器数据库(DefaultConnection)。
(在应用程序之后对我来说没有用,只有在需要构建之后)
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.
...
请在回答之前,仅在 blazor web 应用程序 8.0 中检查您的解决方案,tnks。
不工作:
如果您希望根据请求中的某些信息(例如“主机名”来确定请求是否来自本地)使用不同的ConnectionString,您可以使用不同的ConnectionString注册两个DbContext(例如“MyContext1”和“MyContext2”)。然后为它们创建一个接口,例如“IMyContext”,以下代码将让IMyContext根据请求解析不同的服务。
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>();
}
});