【问题标题】:How to read connection string from data access layer in asp.net 5如何从asp.net 5中的数据访问层读取连接字符串
【发布时间】:2016-01-27 20:32:29
【问题描述】:

随着新的 ASP.NET 5 取消了 web.config,从而取消了 ConfigurationManagement 命名空间,我试图弄清楚如何从我的 MVC 应用程序中的数据访问层项目中读取连接字符串。

研究这个问题,我发现的一切都说只是从 Startup.cs 文件中的 project.json 配置文件中读取配置值,如下所示:

var configuration = new Configuration();
configuration.AddJsonFile("config.json");
configuration.AddEnvironmentVariables();

//////

var connString = configuration.Get("Data:DefaultConnection:ConnectionString");

但我不希望我的网络项目与数据访问有任何关系。那么,我的数据访问层项目如何检索此设置中的连接字符串?

更新:这是我的 startup.cs 文件和 ConfigureServices 方法:

public void ConfigureServices(IServiceCollection services)
{
    // Add Identity services to the services container.
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    // Add MVC services to the services container.
    services.AddMvc();

    // Register application services.
    services.Configure<ApplicationOptions>(options =>
    {
        options.ConnectionString = "Data:DefaultConnection:ConnectionString";
    });
}

这是我的 DataAccessLayer 项目和我的 RepoBase.cs 类

public class RepoBase
{
    //private readonly string _connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    //private readonly string _connectionString = Environment.GetEnvironmentVariable("ConnectionString");
    private readonly string _connectionString;

    public RepoBase(IOptions<ApplicationOptions> appOptions)
    {
        this._connectionString = appOptions.ConnectionString;

        // or just read directly from System.Configuration.Get("");
    }

    protected SqlConnection GetConnection()
    {
        var conn = new SqlConnection(_connectionString);
        conn.OpenAsync();

        return conn;
    }
}

这是我关于如何在我的 DAL 项目中检索我的 ApplicationOptions 对象的空白,或者只是读取在 Startup.cs 中设置的连接字符串值

configuration.AddEnvironmentVariables()

方法调用。

更新 2: 哦,这是我需要从我的数据访问层访问环境变量的东西吗:https://github.com/aspnet/configuration/blob/master/src/Microsoft.Extensions.Configuration.EnvironmentVariables/EnvironmentVariablesConfigurationProvider.cs

【问题讨论】:

  • 如果DA层是DLL,应该可以读取消费应用的project.json文件。如果它是它自己的应用程序,它将有它自己的 project.json 文件。除非我遗漏了方程式的一部分?
  • 让您的 Web 项目检索连接字符串并将其传递给数据层没有任何问题。或者,Web 项目可以将其整个配置传递给数据层,然后数据层可以从配置中挑选出它想要的内容。
  • @Tim 就像你说的,它只是一个单独的 DLL。
  • @mason 既然 ConfigurationManager 不再工作,那么将使用什么命名空间?
  • ASP.NET 5 已死:hanselman.com/blog/… 很抱歉您的损失

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


【解决方案1】:

这是this的副本

在您的 ConfigureServices 方法中,将您的配置对象添加为单例。

public void ConfigureServices(IServiceCollection services) {
    services.AddSingleton(_ => configuration);
}

然后像这样更新你的 BaseRepo 类

public class BaseRepo {
    private readonly IConfigurationRoot config;

    public BaseRepo(IConfigurationRoot config) {
        this.config = config;
    }

    public static SqlConnection GetOpenConnection() {
        var cs = config.Get<string>("Data:DefaultConnection:ConnectionString");
        var connection = new SqlConnection(cs);
        connection.Open();
        return connection;
    }
}

【讨论】:

  • 这还有一个问题。数据访问类 (BaseRepo) 位于单独的 DLL 中,因此可能可以在其他应用程序中使用。因为 BaseRepo 直接从 IConfigurationRoot (appsettings.json) 读取 ConnectionString,所以这会强制所有客户端对该 ConnectionString 使用相同的名称(键)。将 ConnectionString 和 appsettings.json 中的其他值输入到 BaseRepo 构造函数会更好吗?如何使用 .NET 5 依赖注入来做到这一点?然后另一个应用程序可以在它的 appsettings.json 文件中将连接字符串称为其他内容。
【解决方案2】:
        //inside this mehtod connection string is used
        public DataTable GetDataTable(string cmdText)
        {
            DataTable dt = new DataTable();           
            var constr = OnConfiguring(); //this method is called to get connection string

            using (SqlConnection con = new SqlConnection(constr))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmdText, con);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.Fill(dt);
            }
            return dt;
        }
    }
}

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案3】:

//该方法用于返回连接字符串

            protected  string OnConfiguring() 
            {

                var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).
                    AddJsonFile("appsettings.json", optional: true,
                    reloadOnChange: true);
appsettings.json file            
                string dbConnection = builder.Build().GetSection("ConnectionStrings").GetSection("DevConnections").Value;
                return dbConnection;
            }

【讨论】:

  • 如果您打算在 dot net core 中使用 ADO.net 或 3 层代码,这是访问连接字符串的最佳方式。
  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多