Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

c# - .NET Core get connection string from appsettings.json

I develop a simple web app and, in the future, I want to do it as multi-tenancy.

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);
    }
}

Startup class:

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

How can I extract connection string from appsettings.json into ApplicationContext class?

I wouldn't like to create any constructors for ApplicationContext class.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's imagine that you have .NET Core application and your appsettings.json file looks like this:

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

You can get SqliteConnectionString value from Startup.cs like this:

public void ConfigureServices(IServiceCollection services)
{
    var connection = Configuration["Production:SqliteConnectionString"];

    services.AddDbContext<MyContext>(options =>
        options.UseSqlite(connection)
    );
    ....
 }

And then in your DBContext you should add constructor that accepts DbContextOptions:

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

    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...