我有 appsettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionString": "Server=...;Database=...;Trusted_Connection=True;"
}
和数据库类
public class Database : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer(@"Server=...;Database=...;Trusted_Connection=True;");
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Material>().ToTable("vw_Material", schema: "query");
}
public virtual DbSet<Material> Material { get; set; }
}
我的问题是,如何替换此行
optionsBuilder.UseSqlServer(@"Server=...;Database=...;Trusted_Connection=True;");
具有来自appsettings的价值吗?
答案 0 :(得分:5)
您可以为此使用DI。为此,您需要在Startup.cs中注册配置:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IConfiguration>(Configuration);
}
然后您可以将其注入数据库构造函数:
private readonly IConfiguration configuration;
public Database(IConfiguration config)
{
configuration = config;
}
并在配置时访问它:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer(configuration.GetConnectionString("ConnectionString"));
另一个选项是使用“选项”模式。在这种情况下,您必须使用所需的属性创建一个类:
public class ConnectionStringConfig
{
public string ConnectionString { get; set; }
}
在启动时注册:
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<ConnectionStringConfig>(Configuration);
}
注入数据库构造函数:
private readonly ConnectionStringConfig configuration;
public Database(IOptions<ConnectionStringConfig> config)
{
configuration = config.Value;
}
并在配置时访问它:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer(configuration.ConnectionString);