问题描述
我开发了一个简单的Web应用程序,将来,我希望将其作为多租户来使用。
I develop a simple web app and, in the future, I want to do it as multi-tenancy.
所以我想将连接字符串直接写入 OnConfiguring
方法:
So I want to write the connection string straight into OnConfiguring
method:
public class ApplicationContext : DbContext
{
public DbSet<User> 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<ApplicationContext>();
services.AddMvc();
}
如何从 appsettings.json中提取连接字符串
放入 ApplicationContext
类?
我不想为 ApplicationContext
类。
推荐答案
如何从appsettings.json中提取连接字符串到ApplicationContext类中?
How can I extract connection string from appsettings.json into ApplicationContext class?
我不想为ApplicationContext类创建任何构造函数。
I wouldn't like to create any constructors for ApplicationContext class.
您可以使用 Options Pattern 通过 IOptions
,但是最简单的方法是在 ApplicationContext
构造函数中使用DI;)
You could use Options Pattern via IOptions
but the easiest way is using DI in ApplicationContext
constructor ;)
请关注以下文章,
- ,
- ,
- ,
- Example of using IOptions,
- Using Options and configuration objects,
- IOptions Interface,
这篇关于.NET Core从appsettings.json获取连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!