83 lines
2.1 KiB
Markdown
83 lines
2.1 KiB
Markdown
# DbContext 工厂
|
||
|
||
> 所属模块:[数据库支持](./概览.md)
|
||
|
||
---
|
||
|
||
## 1. 本地库工厂
|
||
|
||
```csharp
|
||
// Infrastructure/LocalData/IDbContextFactory.cs
|
||
namespace Gpulse.WCT.DataAnalyzer.Core.Infrastructure.LocalData;
|
||
|
||
public interface IDbContextFactory
|
||
{
|
||
WctMinerDbContext CreateDbContext();
|
||
}
|
||
```
|
||
|
||
工厂实现读取 `Database:LocalPath`(fallback `Database:Path`),支持 SQLite 和 PostgreSQL。
|
||
|
||
---
|
||
|
||
## 2. 发布库工厂
|
||
|
||
```csharp
|
||
// Infrastructure/ReleaseData/IReleaseDbContextFactory.cs
|
||
namespace Gpulse.WCT.DataAnalyzer.Core.Infrastructure.ReleaseData;
|
||
|
||
public interface IReleaseDbContextFactory
|
||
{
|
||
ReleaseDbContext CreateDbContext();
|
||
}
|
||
```
|
||
|
||
工厂实现读取 `Database:ReleasePath`,支持 SQLite 和 PostgreSQL。PostgreSQL 时使用 `Release*` 前缀配置(`ReleaseHost`, `ReleasePort`, `ReleaseName`, `ReleaseUser`, `ReleasePassword`),未设置时回退到 local 的对应配置。
|
||
|
||
---
|
||
|
||
## 3. DI 注册
|
||
|
||
```csharp
|
||
// Infrastructure/Extensions/ServiceCollectionExtensions.cs
|
||
public static IServiceCollection AddDatabaseServices(
|
||
this IServiceCollection services,
|
||
IConfiguration configuration)
|
||
{
|
||
// 本地库
|
||
services.AddScoped<IDbContextFactory, DbContextFactory>();
|
||
services.AddScoped<WctMinerDbContext>(sp =>
|
||
{
|
||
var factory = sp.GetRequiredService<IDbContextFactory>();
|
||
return factory.CreateDbContext();
|
||
});
|
||
|
||
// 发布库(独立)
|
||
services.AddScoped<IReleaseDbContextFactory, ReleaseDbContextFactory>();
|
||
services.AddScoped<ReleaseDbContext>(sp =>
|
||
{
|
||
var factory = sp.GetRequiredService<IReleaseDbContextFactory>();
|
||
return factory.CreateDbContext();
|
||
});
|
||
|
||
return services;
|
||
}
|
||
```
|
||
|
||
## 4. 启动初始化
|
||
|
||
```csharp
|
||
// Program.cs
|
||
using var scope = app.Services.CreateScope();
|
||
|
||
// 初始化本地库
|
||
var dbContext = scope.ServiceProvider.GetRequiredService<WctMinerDbContext>();
|
||
await dbContext.Database.EnsureCreatedAsync();
|
||
|
||
// 初始化发布库
|
||
var releaseContext = scope.ServiceProvider.GetRequiredService<ReleaseDbContext>();
|
||
await releaseContext.Database.EnsureCreatedAsync();
|
||
|
||
// 本地库种子数据
|
||
SeedData.Initialize(dbContext);
|
||
``` |