Partilhar via


How to Connect to Managed Cache Service using the code and not with typical way of configuration?

Here's a sample code to connect to Managed Cache Service, which we typically connect using Cache Configuration in the configuration file.

            var cacheSvcUri = "<your cache>.cache.windows.net";
            var cacheSvcAcsKey = "<your key>";
            var secureAcsKey = new SecureString();
            foreach (char c in cacheSvcAcsKey)
            {
                secureAcsKey.AppendChar(c);
            }
            secureAcsKey.MakeReadOnly();
            DataCacheFactoryConfiguration dcfConfig = new DataCacheFactoryConfiguration();
            dcfConfig.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(false);
            // Set autodiscover for in-role/managed cache
            dcfConfig.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, cacheSvcUri);
            DataCacheSecurity factorySecurity = new DataCacheSecurity(secureAcsKey);
            dcfConfig.SecurityProperties = factorySecurity;
            var dcf = new DataCacheFactory(dcfConfig); // make the DataCacheFactory static as it connects to the cache cluster.
            //var cache = dcf.GetDefaultCache(); //This times out all the time
            var cache = dcf.GetDefaultCache();
            cache.Put("One", 1);
            cache.Put("Two", 2);

Also, here's the documentation on DataCacheFactoryConfiguration class.

https://msdn.microsoft.com/en-us/library/microsoft.applicationserver.caching.datacachefactoryconfiguration.aspx