本文介绍了.NET Core 从 appsettings.json 获取连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个简单的网络应用程序,并且在未来我想将其作为多租户来实现.

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 类中?

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

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

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

推荐答案

如何将 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.

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

You could use Options Pattern via IOptions but the easiest way is using DI in ApplicationContext constructor ;)

请关注以下文章:

这篇关于.NET Core 从 appsettings.json 获取连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:41