[英]How to get connection string in class library project
In my .net solution, I have two different projects: An MVC core web application project and a class library project. 在我的.net解决方案中,我有两个不同的项目:MVC核心Web应用程序项目和类库项目。 In web application project, database connection string is in appsettings.json
file. 在Web应用程序项目中,数据库连接字符串位于appsettings.json
文件中。 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. 如果有更好的方法来获取连接字符串,请告诉我。
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. 在实际应用程序中,最好使用依赖注入技术注入连接字符串或通过构造函数公开连接字符串的设置。
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. 从Web应用程序调用类库时,请不要担心,将从Web应用程序应用程序设置文件中检索连接字符串。
For more info, see Get connection String 有关更多信息,请参阅获取连接字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.