You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Blazor及控制台应用中从类库获取数据库连接字符串?

解决方案:共享连接字符串与遵循SOLID的最佳实践

一、核心思路

类库只负责定义业务与数据访问逻辑,配置(如连接字符串)应由客户端应用提供——这符合SOLID中的依赖倒置原则(高层与底层模块均依赖抽象)和单一职责原则(类库专注核心逻辑,不处理配置读取)。

二、步骤1:优化类库设计

1. 移除硬编码配置,强制依赖注入

修改DataContext.cs,删除默认构造函数和OnConfiguring中的硬编码逻辑,确保类库必须通过外部传入的配置初始化:

using Microsoft.EntityFrameworkCore;
using Schowek.Library.Models;

namespace Schowek.Library.Data
{
    public class DataContext : DbContext
    {
        // 仅保留带参数的构造函数,强制通过依赖注入传入配置
        public DataContext(DbContextOptions<DataContext> options) : base(options) { }

        public DbSet<Catalog>? Catalogs { get; set; } = null!;
        public DbSet<Item>? Items { get; set; } = null!;
    }
}

2. 标准化配置契约(可选但推荐)

在类库中定义配置键名的常量类,避免客户端拼写错误,统一配置标准:

namespace Schowek.Library.Configuration
{
    public static class ConnectionStringNames
    {
        public const string Default = "DevelopmentConnection";
    }
}

三、步骤2:Blazor WASM应用集成

1. 复用类库配置文件

将类库中的appsettings.json复制到Blazor WASM项目的wwwroot目录(Blazor WASM仅能读取该目录下的配置文件),确保配置复用。

2. 读取配置并注册DbContext

修改Blazor的Program.cs,从配置中读取连接字符串并传入UseSqlite:

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.EntityFrameworkCore;
using Schowek.Client.BlazorWASM;
using Schowek.Library.Data;
using Schowek.Library.Interfaces;
using Schowek.Library.Repositories;
using Schowek.Library.Configuration;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

// 从配置文件读取连接字符串
var connectionString = builder.Configuration.GetConnectionString(ConnectionStringNames.Default);
builder.Services.AddDbContext<DataContext>(options =>
{
    options.UseSqlite(connectionString);
});

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<ICatalogRepository, CatalogRepository>();

await builder.Build().RunAsync();

四、步骤3:控制台应用集成

1. 复用类库配置文件

将类库中的appsettings.json复制到控制台项目根目录,设置文件属性为「复制到输出目录:如果较新则复制」。

2. 加载配置并初始化DbContext

控制台应用需手动加载配置文件,再注册并使用服务:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Schowek.Library.Data;
using Schowek.Library.Interfaces;
using Schowek.Library.Repositories;
using Schowek.Library.Configuration;

// 加载配置文件
var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

// 注册服务
var services = new ServiceCollection();
var connectionString = configuration.GetConnectionString(ConnectionStringNames.Default);
services.AddDbContext<DataContext>(options =>
{
    options.UseSqlite(connectionString);
});
services.AddScoped<ICatalogRepository, CatalogRepository>();

// 构建服务容器并使用
using var serviceProvider = services.BuildServiceProvider();
var catalogRepo = serviceProvider.GetRequiredService<ICatalogRepository>();
// 执行业务逻辑...

五、遵循SOLID原则的最佳实践

  1. 单一职责原则:类库专注业务与数据逻辑,配置读取由客户端负责;DataContext仅管理数据库上下文,不处理配置来源。
  2. 依赖倒置原则:客户端注入DbContextOptions给DataContext,类库依赖抽象(DbContextOptions)而非具体配置实现。
  3. 开放/封闭原则:后续更换数据库(如SQL Server)时,仅需修改客户端的配置和数据库驱动方法,类库无需改动。
  4. 接口隔离原则:类库通过ICatalogRepository等接口暴露能力,客户端仅依赖所需接口,而非具体实现。

六、配置复用的进阶技巧

若要避免手动复制配置文件,可将类库的appsettings.json添加为客户端项目的链接文件:右键客户端项目→添加→现有项→选择类库的配置文件→点击添加按钮的下拉箭头→选择「添加为链接」,再设置复制属性。修改类库配置时,客户端的链接文件会同步更新。

内容的提问来源于stack exchange,提问作者Sisimośki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:40:42