.NET Core get connection string from appsettings.json

后端 未结 4 2034
执笔经年
执笔经年 2020-12-16 11:22

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 me

4条回答
  •  既然无缘
    2020-12-16 12:13

    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(options =>
            options.UseSqlite(connection)
        );
        ....
     }
    

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

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

提交回复
热议问题