ConnectionString from app.config of a DLL is null

血红的双手。 提交于 2019-11-29 08:21:16

I have a class library that contains a valid connectionString inside the app.config

A class library doesn't have an app.config file associated. It's the application consuming this assembly that does. So you need to put the connection string inside this config file (if this is an ASP.NET application this would be web.config). Thus adding an App.config file in a project of type class library in Visual Studio makes no sense.

In this case you put the same <connectionStrings> entry (the <add> in question) in your web app's web.config, ConfigurationManager.ConnectionStrings always looks at the current config, that's a web.config in your case.

In case if you don't waana use ConfigurationManager

If i assume the config file is mydll.dll.config i can load it as XElement and parse it using Linq as

var xe = XElement.Load("mydll.dll.config");
var connectionString = xe.Descendants("connectionStrings")
     .Elements("add")
     .FirstOrDefault(a => a.Attribute("name").Value == Name)
     .Attribute("connectionString").Value;

where Name is the connectionString name in the XML. Without using the ConfigurationManager import and other stuffs. The only requirement for this to make sure that the config file sit next to the dll.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!