如何从Blazor .NET Core项目连接到多个数据库? [英] How can I connect to multiple databases from a Blazor .NET Core project?
问题描述
如何从Blazor WebAssembly项目连接到多个数据库实例,在该项目中我还添加了托管的ASP.NET Core?
How do I connect to multiple database instances from a Blazor WebAssembly project, where I have also added the ASP.NET Core hosted?
我的想法是将 DBContexts
初始化为"Startup.cs"(来自Blazor.Server应用程序,该应用程序引用了Blazor.Client应用程序):
My thought was to initiate the DBContexts
into the `Startup.cs`` (from Blazor.Server Application which has a reference to Blazor.Client Application):
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DatabaseContext>(options =>
options.UseSqlite(
"connection string holder ..."));
}
像这样,但是我想让用户在我的视图中选择是否要对将在其中创建SQLite数据库实例的App进行测试运行.常规运行将是SQL Server数据库的一个实例.如何在ConfigureServices方法中执行此操作?
like this but I want to let the user choose in my View if they want to do a test run of the App where the SQLite database instance will be created. The regular run will be an instance to SQL Server database. How can I do this in the ConfigureServices method?
现在我正在构建 DBContexts
类,这些类也会影响吗?
Right now I am building the DBContexts
classes, are these effected too?
控制器尚未完成,ASP.NET Core MVC控制器是正确的选择吗?
The controllers are not done yet, are ASP.NET Core MVC controllers the right choice?
推荐答案
您可以使用2个数据库上下文,一个接口和一项从API请求中发送的数据中选择上下文的服务来实现该目标:
You can implement that using 2 DB contexts, one interface and a service choosing the context from data sent in API requests:
数据库上下文界面
public interface IDatabaseContext
{
// add all DbSet declaration here
}
数据库上下文
public class DatabaseContext : IDatabaseContext
{
// db context implementation
}
测试数据库上下文
public class TestDatabaseContext: DatabaseContext
{
// add your constructor
}
DbContext解析器服务
public class DbContextResolver
{
public bool IsTest { get; set; }
服务器端DI设置
services.AddDbContext<DatabaseContext>(options =>
options.UseSqlServer(
"SqlServer connection string holder ..."))
.AddDbContext<TestDatabaseContext>(options =>
options.UseSqlite(
"Sqlite connection string holder ..."))
.AddScoped<DbContextResolver>())
.AddScoped<IDatabaseContext>(p =>
{
var resolver = p.GetRequiredService<DbContextResolver>();
if (resolver.IsTest)
{
retrun p.GetRequiredService<TestDatabaseContext>();
}
return p.GetRequiredService<DatabaseContext>();
}));
从请求中选择数据库上下文
public void Configure(IApplicationBuilder app)
{
app.Use((context, next) =>
{
var resolver = context.RequestServices.GetRequiredService<DbContextResolver>();
resolver.IsTest = context.Request.Query.ContainsKey("test"); // here the context is choosed by query string but you can choose to send an header instead
return next();
}
}
在控制器或服务中使用所选的数据库上下文
public class MyController : Controller
{
public MyController(IDatabaseContext context)
...
}
这篇关于如何从Blazor .NET Core项目连接到多个数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!