【问题标题】:How can you have and access a variable amount of connection strings in .net core (not strongly typed)?如何在 .net 核心(非强类型)中拥有和访问可变数量的连接字符串?
【发布时间】:2016-11-09 15:40:09
【问题描述】:

在 ASP.NET 4.6 中,web.config 中有一个 connectionStrings 部分,您可以在其中添加无限量的连接字符串并将它们动态读入应用程序或按名称获取单个连接字符串。

我看到的 ASP.NET Core 示例使用 appsettings.json 文件来存储设置,然后将这些设置绑定到具有与设置名称匹配的属性的强类型对象。具有设置值的绑定对象存储在一个容器中,以便在您的应用程序周围注入。

我需要在 appsettings.json 中有一个连接字符串列表,并允许用户在运行时(当他们登录时)选择数据库。我会将用户连接到的数据库的名称存储为声明。但是,我需要能够在整个应用程序中注入或以某种方式访问​​连接字符串列表,以便我可以获得用户连接到的数据库的连接字符串。另外,我需要能够向实体框架提供连接字符串。

【问题讨论】:

  • 最简单的方法是在您需要从那里注入并创建数据库的任何地方使用工厂模式。然后为您的 DbContext 注册工厂:services.AddScoped<MyDbContext>(provider => provider.GetService<MyDbContextFactory>().Create()); 没有时间获得更详细的答案

标签: c# asp.net-core asp.net-core-mvc asp.net-core-1.0


【解决方案1】:

appsettings.json 在存储和访问 ConnectionStrings 方面与 web.config 具有相同的功能

{
  "ConnectionStrings": {
    "SqlServerConnection" : "Server=.\\sql2012express;Database=aspnet-IdentityServer4WithAspNetIdentity;Trusted_Connection=True;MultipleActiveResultSets=true",
    "SqLiteConnection": "Data\\LynxJournal.db"
  },
}

这些可以通过代码访问

_config.GetConnectionString("SqliteConnection")

其中 SqlliteConnection 是连接字符串的名称

_config 来自于从 Startup.cs 注入 IConfiguration 服务,其中配置设置在

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();

        Environment = env;
    }

    public IConfigurationRoot Configuration { get; }
    private IHostingEnvironment Environment { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
        services.AddEntityFrameworkSqlite().AddDbContext<LynxJournalDbContext>();


        services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();


        services.AddSingleton<IConfiguration>(Configuration);
        services.AddSingleton<IHostingEnvironment>(Environment);

        Services = services;
    }

【讨论】:

    猜你喜欢
    • 2021-03-09
    • 2017-05-02
    • 2019-09-22
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多