I have a class library that contains classes shared by an asp.net web application and a WCF web service. The classes inside the library need to retrieve information from the database, and so the library has an entry in the app.config for the connection string, and a method that retrieves that connection string.
Here's how I declare my connection string in the app.config :
<configuration>
<connectionStrings>
<add name="connstring"
connectionString="Data Source=MYSERVER;Initial Catalog=MY_DB;User Id=mylogin;Password=mypassword;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
[...]
</configuration>
And here's the method that retrieves the connection string :
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data.OleDb
Public Module modGen
Public Function gGetConnectionString() As String
Dim conn As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("connstring")
Dim connString As String = conn.ConnectionString
Return connString
End Function
The problem is that, when the method runs, "conn" gets "Nothing" for value and the following exception is then thrown :
System.TypeInitializationException was caught
Message=The type initializer for 'CHK.TRK.CLS.modGen' threw an exception.
Source=CHK.TRK.CLS
TypeName=CHK.TRK.CLS.modGen
StackTrace:
at CHK.TRK.CLS.modGen.gGetConnectionString()
at CHK.TRK.CLS.modAuth.CheckUser(String logon, String pwHash) in H:\WorkSpace\CHKTRK\CHKTRK\CHKTRKClasses\Mod\modAuth.vb:line 141
at CHK.TRK.CLS.modAuth.Authenticate(String logon, String pwhash) in H:\WorkSpace\CHKTRK\CHKTRK\CHKTRKClasses\Mod\modAuth.vb:line 9
at CHKTRKWebService.CheckTrackService.Authenticate(String login, String pwHash) in H:\WorkSpace\CHKTRK\CHKTRK\CHKTRKWebService\CheckTrackService.svc.vb:line 20
InnerException: System.NullReferenceException
Message=Object reference not set to an instance of an object.
Source=CHK.TRK.CLS
StackTrace:
at CHK.TRK.CLS.modGen..cctor() in H:\WorkSpace\CHKTRK\CHKTRK\CHKTRKClasses\Mod\modGen.vb:line 138
InnerException:
Is there something wrong with the way I declare my connection string in the app.config file, or with the method that retrieves it ?