ConnectionString from app.config of a DLL is null

10,844

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
10,844
citronas
Author by

citronas

I studied computer science and math and completed my academic career with a PhD in computer science about machine learning and argument mining on text data. I've returned to the corporate sector and am currently working as a Senior Software Developer for a digital media agency where I focus on designing and implementing solutions with ASP.NET Core MVC and C#.

Updated on June 17, 2022

Comments

  • citronas
    citronas almost 2 years

    I have a class library that contains a valid connectionString inside the app.config. Inside that class library I want to use it with

    ConfigurationManager.ConnectionStrings["NAME"].ConnectionString
    

    My ASP.net 4.0 framework application references that DDL and retrieves data from it. I want create a Entity Framework 4 DataContext within my DDL with the ConnectionString from the App.config. (I do not want to pass the connectionString from my ASP.net application in every single method. (I'm using ObjectDataSources))

    However, this line inside my DLL throws a NullReferenceException.

    ConfigurationManager.ConnectionStrings["NAME"].ConnectionString
    

    How can I fix this issue?