在解决方案中获取类库项目中的连接字符串 [英] Get connection string in class library project in a solution

查看:210
本文介绍了在解决方案中获取类库项目中的连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的.net 4解决方案中,我有两个不同的项目 - 一个Web应用程序项目和一个类库项目。



在Web应用程序项目中,数据库连接字符串是在web.config文件。我想从类库项目中访问该连接字符串。可能吗?如果是的话,怎么样?



如果有更好的方法来获取连接字符串,请让我知道。

解决方案

要从您的类库访问它,请添加对 System.Configuration 的引用,然后使用 System.Confinguration。 ConfigurationManager.ConnectionStrings



从类库读取这个不太理想。毕竟,你能说你的类库总是被配置文件的东西所消耗吗?当然,如果你和其他开发者,特别是不同的平台分享,那么不要。



考虑:


  1. IoC - 使用依赖注入来提供包含配置设置的依赖项。这些将由消费库(网络应用程序)填充。

  2. 消费依赖于它们的元素时,将设置传递给类库。

例如:

  public class MyLibraryContainer 
{
私有字符串_connectionString;

public MyLibraryContainer(string connectionString)
{
_connectionString = connectionString;
}
}


In my .net 4 solution, i have two different projects- an web application project and a class library project.

In web application project, database connection string is in web.config file. I would like to access that connection string from class library project. Is it possible? if yes, how?

If there is any better approach to get connection string, please let me know.

解决方案

To access it from your class library add a reference to System.Configuration then use System.Confinguration.ConfigurationManager.ConnectionStrings.

It's not ideal to read this from a class library. After all, can you say that your class library will always be consumed by something with a configuration file? Certainly not if you share it with other developers, especially of different platforms.

Consider:

  1. IoC - use dependency injection to provide a dependency that contains configuration settings. These would be populated by the consuming library (web app).
  2. Pass the settings to the class library when consuming elements that depend on them.

e.g.:

public class MyLibraryContainer
{
    private string _connectionString;

    public MyLibraryContainer(string connectionString)
    {
        _connectionString = connectionString;
    }
}

这篇关于在解决方案中获取类库项目中的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆