[英]read connectionstring from WebConfig file in dll
I have a class library project(dll)
and an MVC
project(I'm using ASP.net Core
with .net
framework). 我有一个
class library project(dll)
和一个MVC
项目(我正在将ASP.net Core
与.net
框架一起使用)。 How can I read the connectionstring
that is inside the WebConfig
file of my MVC project in the dll
? 如何读取
dll
中我的MVC项目的WebConfig
文件内的connectionstring
WebConfig
? I'm inside the dll
and I need to read it, I don't want to put the connectionstring
hardcoded in there too if I have it already inside the WebConfig of the MVC project, how could I do that? 我在
dll
并且需要阅读它,如果我已经在MVC项目的WebConfig中安装了connectionstring
字符串,那么我也不想在其中放入硬编码的connectionstring
字符串。 I'm using in my dll this code but it's not working: 我在我的dll中使用此代码,但无法正常工作:
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
Pass the connection string in as an argument when you use / instantiate your class from the class library rather than attempting to access web.config directly from the class library. 使用/实例化类库中的类时,而不是尝试直接从类库中访问web.config时,将连接字符串作为参数传递。 This is a fairly common practice and will be more recognizable to other people who may need to maintain your code.
这是相当普遍的做法,可能需要维护您的代码的其他人会更容易理解。
//in the MVC code somewhere
string conStr = null;
if(ConfigurationManager.ConnectionStrings["MyConnectionStringName"] != null)
conStr = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
else
{
//connection string not found
}
//instantiating class from the class library
var myFoo = new Foo(conStr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.