DocumentDB .Net client using connection string

后端 未结 4 1633
野性不改
野性不改 2021-01-17 14:37

I checked the MSDN on DocumentDB for .Net (here) and found 3 valid constructors. However none of them makes use of connection strings, which sounds strange for me.

I

4条回答
  •  庸人自扰
    2021-01-17 15:17

    You can actually do this in a roundabout way.

    internal class CosmosDBConnectionString
    {
        public CosmosDBConnectionString(string connectionString)
        {
            // Use this generic builder to parse the connection string
            DbConnectionStringBuilder builder = new DbConnectionStringBuilder
            {
                ConnectionString = connectionString
            };
    
            if (builder.TryGetValue("AccountKey", out object key))
            {
                AuthKey = key.ToString();
            }
    
            if (builder.TryGetValue("AccountEndpoint", out object uri))
            {
                ServiceEndpoint = new Uri(uri.ToString());
            }
        }
    
        public Uri ServiceEndpoint { get; set; }
    
        public string AuthKey { get; set; }
    }
    

    Then

    var cosmosDBConnectionString = new CosmosDBConnectionString(connectionString)
    var client = new DocumentClient(
                cosmosDBConnectionString.ServiceEndpoint,
                cosmosDBConnectionString.AuthKey)
    

    This is taken from the Azure WebJobs Extensions SDK, which is how Azure Functions V2 is able to work with just a connection string. Saves having to try and parse the string yourself.

提交回复
热议问题