如何在类库项目中获取连接字符串 [英] How to get connection string in class library project

查看:139
本文介绍了如何在类库项目中获取连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的.net解决方案中,我有两个不同的项目:MVC核心Web应用程序项目和类库项目.在Web应用程序项目中,数据库连接字符串位于appsettings.json文件中.我想从类库项目访问该连接字符串.是否有可能?如果是,怎么办?如果有更好的方法来获取连接字符串,请告诉我.

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.

推荐答案

要举一个简单而简单的示例,您可以在类库中创建一个代表单例或环境上下文的类以提供连接字符串:

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.

这篇关于如何在类库项目中获取连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆