Files
WCTDataMiner/docs/architecture/database/DbContext工厂.md
Scottxjw 2b031995e1 docs: 更新项目架构与数据模型文档
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-13 15:01:32 +08:00

83 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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);
```