How to get connection string in class library project

不羁的心 提交于 2019-12-14 03:48:36

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/43389530/how-to-get-connection-string-in-class-library-project

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