In my .net solution, I have two different projects: An MVC core web application project and a class library project. In web application project, database connection string is in appsettings.json
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.
Asked
Active
Viewed 6,920 times
5

Manfred Radlwimmer
- 13,257
- 13
- 53
- 62

user7861419
- 51
- 1
- 3
-
Are you running .Net Core? Your question doesn't seem to match the tags. – DavidG Apr 13 '17 at 10:17
-
http://stackoverflow.com/questions/15174601/in-c-sharp-global-connection-to-be-used-in-all-classes make your connection string global by using DAL class – Abdul Basit Rana Apr 13 '17 at 10:19
-
Yes I am. My web application is a MVC core application and my class library is a standard class library. – user7861419 Apr 13 '17 at 10:20
-
Why not use a function in your class library like `getConnectionString()` ? – Jones Joseph Apr 13 '17 at 11:17
2 Answers
3
To make simple and trivial example you could create a class in your class library that will represent singleton or ambient context to provide connection string:
public static class ConnectionString
{
public static string Value {get; set;}
}
And then in you app Startup class you set it's value:
var builder = new ConfigurationBuilder()
...
var configuration = builder.Build();
ConnectionString.Value = configuration["connectionString"]; // Or how you do it in your code.
And then you will be able to use it in your class library.
In real-world applications it is better to inject either connection string or settings that exposes connection string via constructor using Dependency injection technics.

Andrii Litvinov
- 12,402
- 3
- 52
- 59
-
@GhanshyamBaravaliya, sure the approach does not depend on a platform. But it makes the config ambient context which is considered an anti-pattern. – Andrii Litvinov May 05 '18 at 09:34
0
Don't worry when your class library is called from the Web application, the connection string will be retrieved from the Web application app settings file.
For more info, see Get connection String