Friday, 20 June 2014

Connecting to Azure Media Services

Before you can start programming against Azure Media Services you need to create a Media Services account in a new or existing Azure subscription. For more info see How to Create a Media Services Account. Once you’ve setup a Media Services account you’ll have connection values for the account in the form of the account name and account key. These values can be stored in configuration and programmatically retrieved to make connections to Media Services.

To code against Media Services you create a CloudMediaContext instance that represents the server context. Media Services controls its access to its services through an OAuth protocol that requires an Access Control Service (ACS) token that is received from an authorisation server. One of the CloudMediaContext constructor overloads takes a MediaServicesCredentials object as a parameter, which enables the reuse of ACS tokens between multiple contexts. You could use a constructor overload that ignores ACS tokens, thus leaving the Media Services SDK to manage them for you. However, this can lead to unnecessary token requests which can create performance issues on both the client and server. The following code example shows how to reuse ACS tokens between multiple contexts.

public class EncodingService
    private static readonly Lazy<MediaServicesCredentials> Credentials =
        new Lazy<MediaServicesCredentials>(() =>
            var credentials = new MediaServicesCredentials(
            return credentials;
    public EncodingService()
       this.context = new CloudMediaContext(EncodingService.Credentials.Value);

The Credentials object is cached in memory as a static class variable that uses lazy initialisation to defer the creation of the object until it is first used. This object contains an ACS token that can be reused if it hasn’t expired. If it has expired it will automatically be refreshed by the Media Services SDK using the credentials given to the MediaServicesCredentials constructor. The cached object is then used by the EncodingService constructor. It’s particularly important to cache your Media Services credentials in a multi-tenant application, otherwise performance issues could occur as a result of thread contention issues.

When the CloudMediaContext instance is created the Credentials object will be created. Using lazy initialisation to do this reduces the likelihood of the MediaServicesCredentials object having to refresh its ACS token due to expiration. For more info about lazy initialisation see Lazy Initialization.

No comments:

Post a Comment