Radim Pluskal
Radim Pluskal

Reputation: 111

How to access Azure SQL Connection string from project Service Dependencies

I started new project of Azure REST API in MS Visual Studio (ASP.NET Core Web Application) and I would like to use project Service Dependencies to manage connection to Azure SQL database. So - I'm created dependency, set name of conn.string, set connection properties, everything look fine ... But now I can't found how to read (get) this connection string in code. Something like this:

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

I found something about dependency injection, but I'm not sure that this is right ... Can you help please?

Upvotes: 0

Views: 742

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89090

Take a dependency on the IConfiguration service.

Eg

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}");
    }
}

Or in your case

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

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

Upvotes: 1

Related Questions