Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

Optimizely will be sunsetting Full Stack Experimentation on July 29, 2024. See the recommended Feature Experimentation migration timeline and documentation.

Dev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideLegal TermsGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Initialize SDK

This topic describes how to initialize the Optimizely C# SDK.

Use the instantiate method to initialize the C# SDK and instantiate an instance of the Optimizely client class that exposes API methods like Get Enabled Features. Each client corresponds to the datafile representing the state of a project for a certain environment.

Version

SDK v3.2.0 and higher

Description

The constructor accepts a configuration object to configure Optimizely.

Some parameters are optional because the SDK provides a default implementation, but you may want to override these for your production environments. For example, you may want override these to set up an error handler and logger to catch issues, an event dispatcher to manage network calls, and a User Profile Service to ensure sticky bucketing.

Parameters

The table below lists the required and optional parameters in C#.

ParameterTypeDescription
datafile
optional
stringThe JSON string representing the project.
configManager
optional
ProjectConfigManagerThe project config manager provides the project config to the client.
eventDispatcher
optional
IEventDispatcherAn event handler to manage network calls.
logger
optional
ILoggerA logger implementation to log issues.
errorHandler
optional
IErrorHandlerAn error handler object to handle errors.
userProfileService
optional
UserProfileServiceA user profile service.
skipJsonValidation
optional
booleanSpecifies whether the JSON should be validated. Set to true to skip JSON validation on the schema, or false to perform validation.
datafile_access_token
optional
string(Server-side only) Optimizely SDKs can use an access token (in combination with an sdkkey) to fetch the datafile from an authenticated endpoint. Find your datafile access token in the Optimizely app at Settings>Environments. Select your secure environment, and copy the _Datafile access token.

Returns

Instantiates an instance of the Optimzely class.

Automatic datafile management (ADM)

Optimizely provides out-of-the-box functionality to dynamically manage datafiles (configuration files) on either the client or the server. The C# SDK provides default implementations of an Optimizely ProjectConfigManager. The package also includes a factory class, OptimizelyFactory, which you can use to instantiate the Optimizely SDK with the default configuration of HttpProjectConfigManager.

Whenever the experiment configuration changes, the SDK uses automatic datafile management (ADM) to handle the change for you. In the C# SDK, you can provide either sdkKey or datafile or both.

  • When initializing with just the SDK key, the SDK will poll for datafile changes in the background at regular intervals.
  • When initializing with just the datafile, the SDK will NOT poll for datafile changes in the background.
  • When initializing with both the SDK key and datafile, the SDK will use the given datafile and start polling for datafile changes in the background.

Basic example

The following code example shows basic C# ADM usage.

using OptimizelySDK;

public class App
{
    public static void Main(string[] args)
    {
        string sdkKey = args[0];
     	 Optimizely optimizely = OptimizelyFactory.NewDefaultInstance(sdkKey);
    }
}

Advanced examples

🚧

Important

If you are configuring a logger, make sure to pass it into the ProjectConfigManager instance as well.

In the C# SDK, you only need to pass the SDK key value to instantiate a client. Whenever the experiment configuration changes, the SDK handles the change for you.

Include sdkKey as a string property in the options object you pass to the createInstance method.

When you provide the sdkKey, the SDK instance downloads the datafile associated with that sdkKey. When the download completes, the SDK instance updates itself to use the downloaded datafile.

🚧

Important

Pass all components (Logger, ErrorHandler, NotificationCenter) to the Optimizely constructor. Not passing a component will fail to enable its respective functionality. In other words, components only work when passed to the constructor.

// Initialize with SDK key and default configuration
var sdkKey = "<Your_SDK_Key>" // replace with your own SDK Key
Optimizely optimizely = OptimizelyFactory.newDefaultInstance(sdkKey);


// You can also customize the SDK instance with custom configuration. In this example we are customizing the project config manager to poll every 5 minutes for the datafile.
var projectConfigManager =
  new HttpProjectConfigManager.Builder()
    .WithSdkKey(sdkKey)
    .WithPollingInterval(TimeSpan.FromMinutes(5))
 // .WithLogger(logger) - this is needed if you are configuring a logger for the optimizely instance
// .WithErrorHandler(errorHandler) - this is needed if you are configuring an errorhandler for the optimizely instance.
// .WithNotificationCenter(notificationCenter) this is needed if you are subscribing config update
    .Build();

var Optimizely = new Optimizely(projectConfigManager);

// Initialize with Logger
// var Optimizely = new Optimizely(projectConfigManager, logger: logger);

// Initialize with Logger, ErrorHandler
// var Optimizely = new Optimizely(projectConfigManager, errorHandler: errorHandler, logger: logger);

// Initialize with NotificationCenter, Logger, ErrorHandler
// var Optimizely = new Optimizely(projectConfigManager, notificationCenter: NotificationCenter, errorHandler: errorHandler, logger: logger);

// Note: Use OptimizelyFactory NewDefaultInstance method to use same logger, errorHandler and notificationCenter for all of its Components (Optimizely, EventProcessor, HttpProjectConfigManager)

Here is a code example showing advanced configuration for C# ADM. Advanced configuration properties are described in the sections below. This advanced example shows how to construct the individual components directly to override various configurations. This gives you full control over which implementations to use and how to use them.

using OptimizelySDK;
using OptimizelySDK.Config;

public class App
{
    public static void Main(string[] args)
    {
        string sdkKey = args[0];
        // You can also use your own implementation of the ProjectConfigManager interface
        ProjectConfigManager projectConfigManager =
        new HttpProjectConfigManager.Builder()
	   .WithSdkKey(sdkKey)
	   .WithPollingInterval(TimeSpan.FromMinutes(1))
	   .Build();

       Optimizely optimizely = new Optimizely(configManager);
    }
}

HttpProjectConfigManager

HttpProjectConfigManager is an implementation of the abstract PollingProjectConfigManager. The Poll method is extended and makes an HTTP GET request to the configured URL to asynchronously download the project datafile and initialize an instance of the ProjectConfig.

By default, HttpProjectConfigManager will block until the first successful datafile retrieval, up to a configurable timeout. Set the frequency of the polling method and the blocking timeout with HttpProjectConfigManager.Builder.

ProjectConfigManager projectConfigManager =
        new HttpProjectConfigManager.Builder()
	 .WithSdkKey(sdkKey)
	 .WithPollingInterval(TimeSpan.FromMinutes(1))
	 .Build();

SDK key

The SDK key is used to compose the outbound HTTP request to the default datafile location on the Optimizely CDN.

Polling interval

The polling interval is used to specify a fixed delay between consecutive HTTP requests for the datafile. The valid interval duration is between 1 to 4294967294 milliseconds.

Initial datafile

You can provide an initial datafile via the builder to bootstrap the ProjectConfigManager so that it can be used immediately without blocking execution. The initial datafile also serves as a fallback datafile if HTTP connection cannot be established. This is useful in mobile environments, where internet connectivity is not guaranteed.

The initial datafile will be discarded after the first successful datafile poll.

Builder methods

Use the following builder methods to customize the HttpProjectConfigManager configuration.

PropertyDefault valueDescription
WithDatafile(string)nullInitial datafile, typically sourced from a local cached source
WithUrl(string)nullURL override location used to specify custom HTTP source for the Optimizely datafile
WithFormat(string)nullParameterized datafile URL by SDK key
WithPollingInterval(TimeSpan)5 minutesFixed delay between fetches for the datafile
WithBlockingTimeoutPeriod(TimeSpan)15 secondsMaximum time to wait for initial bootstrapping. The valid timeout duration is 1 to 4294967294 milliseconds.
WithSdkKey(string)nullOptimizely project SDK key; required unless source URL is overridden

Update config notifications

A notification signal will be triggered whenever a new datafile is fetched. To subscribe to these notifications, use method NotificationCenter.AddNotification().

optimizely.NotificationCenter.AddNotification(
    NotificationCenter.NotificationType.OptimizelyConfigUpdate,
    () => Console.WriteLine("Received new datafile configuration")
);

OptimizelyFactory

OptimizelyFactory provides basic utility to instantiate the Optimizely SDK with a minimal number of configuration options.

OptimizelyFactory does not capture all configuration and initialization options. For more use cases, build the resources with their constructors.

You must provide the SDK key at runtime, directly via the factory method:

Optimizely optimizely = OptimizelyFactory.NewDefaultInstance(<<SDK_KEY>>);

Instantiate using datafile

You can also instantiate with a hard-coded datafile. If you do not pass in an SDK key, the Optimizely Client will not automatically sync newer versions of the datafile. Any time you retrieve an updated datafile, just re-instantiate the same client.

For simple applications, all you need to provide to instantiate a client is a datafile specifying the project configuration for a given environment. For most advanced implementations, you will want to customize the logger or error handler for your specific requirements.

using OptimizelySDK;

// Instantiate an Optimizely client
var datafile = "<Datafile_JSON_string>"
Optimizely OptimizelyClient = new Optimizely(datafile);

Use authenticated datafile in secure environment

You can fetch the Optimizely datafile from an authenticated endpoint using a server-side (only) Optimizely SDK. To use an authenticated datafile, download your Optimizely environment's access token from the Optimizely app at Settings>Environments. Select your secure environment, and copy the Datafile access token. The example below shows how to initialize the Optimizely client using an access token and sdk_key, enabling the client to fetch the authenticated datafile and complete initialization.

// fetch the datafile from an authenticated endpoint
var datafileAccessToken = "<YOUR_DATAFILE_ACCESS_TOKEN>"
var sdkKey = "<YOUR_SKD_KEY>"

var optimizelyClient = OptimizelyFactory.NewDefaultInstance(sdkKey, null, datafileAccessToken);

Source files

The language/platform source files containing the implementation for C# are at Optimizely.cs.