【问题标题】:How to access Azure SQL Connection string from project Service Dependencies如何从项目服务依赖项访问 Azure SQL 连接字符串
【发布时间】:2020-09-24 20:12:00
【问题描述】:

我在 MS Visual Studio(ASP.NET Core Web 应用程序)中启动了 Azure REST API 的新项目,我想使用项目服务依赖项来管理与 Azure SQL 数据库的连接。 所以 - 我创建了依赖项,设置 conn.string 的名称,设置连接属性,一切看起来都很好...... 但是现在我找不到如何在代码中读取(获取)这个连接字符串。像这样的:

 private SqlConnection sqlConnection;
 
 private DataConnector()
 {
    string connectionString = GET_CONSTR_FROM_DEPENDENCY([NameOfMyConnStr]);
    sqlConnection = new SqlConnection(connectionString);
 }

我发现了一些关于依赖注入的东西,但我不确定这是否正确...... 你能帮忙吗?

【问题讨论】:

    标签: c# dependencies azure-sql-database


    【解决方案1】:

    依赖 IConfiguration 服务。

    例如

    public class TestModel : PageModel
    {
        // requires using Microsoft.Extensions.Configuration;
        private readonly IConfiguration Configuration;
    
        public TestModel(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public ContentResult OnGet()
        {
            var myKeyValue = Configuration["MyKey"];
            var title = Configuration["Position:Title"];
            var name = Configuration["Position:Name"];
            var defaultLogLevel = Configuration["Logging:LogLevel:Default"];
    
    
            return Content($"MyKey value: {myKeyValue} \n" +
                           $"Title: {title} \n" +
                           $"Name: {name} \n" +
                           $"Default Log Level: {defaultLogLevel}");
        }
    }
    

    或者在你的情况下

    class DataConnector
    {
      private SqlConnection sqlConnection;
      private DataConnector(IConfiguration config)
      {
        string connectionString = config.GetConnectionString(NameOfMyConnString);
        sqlConnection = new SqlConnection(connectionString);
      }
    }
    

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration

    【讨论】:

      猜你喜欢
      • 2011-09-09
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      相关资源
      最近更新 更多