.NET Core从appsettings.json获取连接字符串

我开发了一个简单的Web应用程序,并且在将来,我希望将其作为多租户来实现。

所以我想直接将连接字符串写入OnConfiguring方法:

 public class ApplicationContext : DbContext { public DbSet Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("connection string from appsettings.json"); base.OnConfiguring(optionsBuilder); } } 

启动课程:

 public void ConfigureServices(IServiceCollection services) { services.AddDbContext(); services.AddMvc(); } 

如何从appsettings.json提取连接字符串到ApplicationContext类?

我不想为ApplicationContext类创建任何构造函数。

所以我想直接将连接字符串写入OnConfiguring方法:

如何从appsettings.json中提取连接字符串到ApplicationContext类?

我不想为ApplicationContext类创建任何构造函数。

您可以通过IOptions使用Options Pattern ,但最简单的方法是在ApplicationContext构造函数中使用DI;)

请按照以下文章:

  • 使用IOptions的示例 ,
  • 使用选项和配置对象 ,
  • IOptions接口 ,

让我们假设你有.NET Core应用程序,你的appsettings.json文件如下所示:

 { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } }, "Production": { "SqliteConnectionString": "Filename=./MyDatabase.sqlite" } } 

您可以从Startup.cs获取SqliteConnectionString值,如下所示:

 public void ConfigureServices(IServiceCollection services) { var connection = Configuration["Production:SqliteConnectionString"]; services.AddDbContext(options => options.UseSqlite(connection) ); .... } 

然后在你的DBContext你应该添加接受DbContextOptions构造DbContextOptions

 public class MyContext : DbContext { public MyContext (DbContextOptions options) : base(options) { } ... } 

.NET Core 2.0

添加此课程:

 // Requires NuGet package Microsoft.Extensions.Configuration.Json using Microsoft.Extensions.Configuration; using System.IO; namespace RutarBackgroundServices.AppsettingsJson { public static class AppSettingsJson { public static string ApplicationExeDirectory() { var location = System.Reflection.Assembly.GetExecutingAssembly().Location; var appRoot = Path.GetDirectoryName(location); return appRoot; } public static IConfigurationRoot GetAppSettings() { string applicationExeDirectory = ApplicationExeDirectory(); var builder = new ConfigurationBuilder() .SetBasePath(applicationExeDirectory) .AddJsonFile("appsettings.json"); return builder.Build(); } } } 

从“appsettings.json”文件中获取键“MssqlConnectionString”的值:

 var appSettingsJson = AppSettingsJson.GetAppSettings(); var connectionString = appSettingsJson["MssqlConnectionString"]; 

在项目的根目录中创建文件“appsettings.json”:

 { "MssqlConnectionString": "Server=yourip; Database=yourdbname; User Id=yourusername; Password=yourpassword; Pooling=true;", "Db2ConnectionString": "Database=yourdbname;UserID=yourusername;Password=yourpassword;Server=yourip:yourport", "SomeOtherKey": "SomeOtherValue" } 

您可以使用工厂模式来解析DbContext

 public interface ITenantDbContextFactory { ApplicationContext Create(string tenantId); } public class TenantDbContextFactory() { private ApplicationContext context; public TenantDbContextFactory() { } public ApplicationContext Create(string tenantId) { if(this.context==null) { var connectionString = GetConnectionForTenant(tenantId); var dbContextBuilder = new DbContextOptionsBuilder(); dbContextBuilder.UseSqlServer(connectionString); this.context = new ApplicationContext(dbContextBuilder); } return this.context; } } 

在初创公司:

 services.AddDbContext(); services.AddScoped(); 

您的服务或控制器:

 public class HomeController { private readonly ITenantDbContextFactory dbFactory; public HomeControler(ITenantDbContextFactory tenantDbContextFactory) { this.dbFactory = tenantDbContextFactory; } public void Action() { var dbContext = this.dbFactory.Create("tenantA"); // use your context here dbContext... } }