简体   繁体   English

如何在类库项目中获取连接字符串

[英]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.

相关问题 在解决方案中获取类库项目中的连接字符串 - Get connection string in class library project in a solution 没有启动项目的实体框架数据库连接字符串和类库? - Entity Framework database connection string and class library without startup project? 如何从ASP.NET Core读取.NET标准类库项目中的连接字符串 - How to read connection string inside .NET Standard Class library project from ASP.NET Core 如何将连接字符串传递给类库? - How to pass connection string to a class library? 类库连接字符串-如何更改? - Class Library Connection String - How to change? 如何访问后端类库项目中客户端应用程序的Web配置文件中存储的连接字符串 - How to access connection string stored in web config file of client application inside back end class library project 如何将连接字符串存储在dll /类库中 - how to store connection string in dll / class library 类库连接字符串混乱 - Class Library Connection String Confusion 迁移如何将连接字符串传递到库项目(.netStandard) - Migration How to pass Connection String into Library Project (.netStandard) 石英消耗时如何将连接字符串传递给类库 - How to pass connection string to class library when consumed by quartz
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM