Movatterモバイル変換


[0]ホーム

URL:


Dev guideRecipesAPI ReferenceChangelog
Dev guideAPI ReferenceRecipesChangelogUser GuideGitHubDev CommunityOptimizely AcademySubmit a ticketLog InFeature Experimentation
Dev guide
All
Pages
Start typing to search…

Initialize the C# SDK

How to initialize the Optimizely Feature Experimentation C# SDK in your application.

Use the builder to initialize the C# SDK and instantiate an instance of the Optimizely Feature Experimentation client class that exposes API methods like theDecide methods.

Version

4.0.0

Description

The constructor accepts a configuration object to configure Optimizely Feature Experimentation.

The SDK provides a default implementation, but you may want to override the optional parameters for your production environments. For example, you can override these to configure anerror handler andlogger to catch issues, anevent dispatcher to manage network calls, and aUser Profile Service to ensure sticky bucketing.

Parameters

The following are the required and optional parameters for initializing the C# SDK:

Parameter

Type

Description

datafileoptional

string

The JSON string representing the project.

configManageroptional

ProjectConfigManager

The project config manager provides the project config to the client.

eventDispatcheroptional

IEventDispatcher

An event handler to manage network calls.

loggeroptional

ILogger

A logger implementation to log issues.

errorHandleroptional

IErrorHandler

An error handler object to handle errors.

userProfileServiceoptional

UserProfileService

A user profile service.

skipJsonValidationoptional

boolean

Specifies whether the JSON should be validated. Set totrue to skip JSON validation on the schema, orfalse to perform validation.

datafileAccessTokenoptional

string

Use an access token (with ansdkKey) to fetch the datafile from an authenticated endpoint.

Find your datafile access token in the Optimizely app atSettings > Environments. Select your secure environment, and copy theDatafile access token. See theUse authenticated datafile in a secure environment section.

defaultDecideOptionsoptional

Array

Array of OptimizelyDecideOption enums. This parameter sets the default decide options applied to all the Decide calls made during the lifetime of the Optimizely client. Additionally, you can pass options to individual Decide methods (does not override defaults).For details ondecide options, seeOptimizelyDecideOption.

withOdpManager(OdpManager)

OdpManager contains the logic supporting Real-Time Audiences for Feature Experimentation-related features, including audiences.

By default, the C# SDK enables the Real-Time Audiences for Feature Experimentation methods. But, the methods do nothing unless you have enabled and configuredReal-Time Audiences for Feature Experimentation.

To optionally disable Real-Time Audiences completely, seeOdpManager.

Returns

Instantiates an instance of the Optimizely class.

Automatic datafile management (ADM)

Optimizely Feature Experimentation 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 OptimizelyProjectConfigManager. The package also includes a factory class,OptimizelyFactory, which you can use to instantiate the Optimizely Feature Experimentation SDK with the default configuration ofHttpProjectConfigManager.

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 asdkKey ordatafile or both.

  • When initializing with just the SDK key – The SDK polls for datafile changes in the background at regular intervals.
  • When initializing with just the datafile – The SDK does not poll for datafile changes in the background.
  • When initializing with both the SDK key and datafile – The SDK uses the given datafile and start polling for datafile changes in the background.

Basic example

The following code example shows basic C# usage.

using OptimizelySDK;public class Program{    public static void Main(string[] args)    {       var sdkKey = args[0];      var optimizely = OptimizelyFactory.NewDefaultInstance(sdkKey);    }}

Advanced examples

🚧

Important

When you configure a logger, you should pass it into theProjectConfigManager 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.

IncludesdkKey as a string property in the options object you pass to theCreateInstance method.

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

🚧

Important

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

// Initialize with SDK key and default configurationconst string sdkKey = "YOUR_SDK_KEY"; // replace with your SDK Keyvar optimizely = OptimizelyFactory.NewDefaultInstance(sdkKey);// You can also customize the SDK instance with custom configuration. // In this example you 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) // needed if you are configuring a logger  // .WithErrorHandler(errorHandler) // needed if you are configuring an error handler  // .WithNotificationCenter(notificationCenter) // needed if you are subscribing config update  .Build();optimizely = new Optimizely(projectConfigManager);// Initialize with Loggeroptimizely = new Optimizely(projectConfigManager, logger: logger);// Initialize with Logger, ErrorHandleroptimizely = new Optimizely(projectConfigManager, errorHandler: errorHandler, logger: logger);// Initialize with NotificationCenter, Logger, ErrorHandleroptimizely = 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. The sections below describe advanced configuration properties. 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 Program{    public static void Main(string[] args)    {      var sdkKey = args[0];            // You can also use your own implementation of the ProjectConfigManager interface      var projectConfigManager = new HttpProjectConfigManager.Builder()        .WithSdkKey(sdkKey)        .WithPollingInterval(TimeSpan.FromMinutes(1))        .Build();      var optimizely = new Optimizely(projectConfigManager);    }}

HttpProjectConfigManager

HttpProjectConfigManager is an implementation of the abstractPollingProjectConfigManager. ThePoll method is extended and makes an HTTPGET request to the configured URL to asynchronously download the project datafile and initialize an instance of theProjectConfig.

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

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

SDK key

The SDK key composes the outbound HTTP request to the default datafile location on the Optimizely CDN.

Polling interval

The polling interval specifies a fixed delay between consecutive HTTP requests for the datafile, using any range supported byTimespan.

Initial datafile

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

The SDK discards the initial datafile after the first successful datafile poll.

Builder methods

Use the following builder methods to customize theHttpProjectConfigManager 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 Feature Experimentation project SDK key; required unless source URL is overridden

Update config notifications

The SDK triggers a notification signal after fetching a new datatfile. To subscribe to these notifications, use theNotificationCenter.AddNotification() method.

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

Note

You must configureReal-Time Audiences for Feature Experimentation to useodpManager.

// Continuing from above.var yourCustomEventQueue = new BlockingCollection<object>(Constants.DEFAULT_QUEUE_CAPACITY);var eventManager = new OdpEventManager.Builder()    .WithEventQueue(yourCustomEventQueue)    .WithOdpEventApiManager(eventApiManager)    .WithFlushInterval(TimeSpan.FromMinutes(3))    .WithTimeoutInterval(TimeSpan.FromSeconds(5))    .WithAutoStart(true)    .WithLogger(logger)    .WithErrorHandler(errorHandler)    .Build();

OptimizelyFactory

OptimizelyFactory provides a basic utility to instantiate the Optimizely Feature Experimentation SDK with minimal 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 using the factory method:

var optimizely = OptimizelyFactory.NewDefaultInstance("YOUR_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 does not automatically sync newer datafile versions. Any time you retrieve an updated datafile, just re-instantiate the same client.

To instantiate a client for simple applications, provide a datafile specifying the project configuration for a given environment. For most advanced implementations, you shouldcustomize the logger orerror handler for your specific requirements.

using OptimizelySDK;// Instantiate an Optimizely clientvar datafile = "YOUR_DATAFILE_JSON_STRING";var optimizely = new Optimizely(datafile);

Use authenticated datafile in a secure environment

You can fetch the datafile from an authenticated endpoint using a server-side (only) Optimizely Feature Experimentation SDK, like the C# SDK.

To use anauthenticated datafile, download your environment's access token from theOptimizely app by going toSettings > Environments. Select your secure environment, and copy theDatafile access token. The following example shows how to initialize the Optimizely client using an access token andsdkKey, enabling the client to fetch the authenticated datafile and complete initialization.

// fetch the datafile from an authenticated endpointvar datafileAccessToken = "YOUR_DATAFILE_ACCESS_TOKEN";var sdkKey = "YOUR_SDK_KEY";var optimizely = OptimizelyFactory.NewDefaultInstance(sdkKey, null, datafileAccessToken);

Dispose of the client

For effective resource management with the Optimizely C# SDK, you must properly close the Optimizely client instance when it is no longer needed. This is done by callingoptimizely.Dispose().

The.Dispose() method ensures that the processes and queues associated with the instance are properly released. This is essential for preventing memory leaks and ensuring that the application runs efficiently, especially in environments where resources are limited or in applications that create and dispose of many instances over their lifecycle.

SeeDispose Optimizely Feature Experimentation C# SDK on application exit.

OdpManager

OdpManager contains the logic supportingReal-Time Audiences for Feature Experimentation.

🚧

Important

You must use .NET Framework version 4.5+ or Standard 2.0+ to use Real-Time Audiences for Feature Experimentation.

By default, the C# SDK enables the Real-Time Audiences for Feature Experimentation methods. But, the methods do nothing unless you have enabled and configuredReal-Time Audiences for Feature Experimentation.

If necessary, to disable Real-Time Audiences for Feature Experimentation altogether, create anew OdpManager.Builder().Build(asEnabled: false) and pass it when instantiating anew Optimizely() instance.

The following settings are configurable when the C# SDK is initialized:

  • ODP SegmentsCache sizecacheSize
    • Default – 10,000
    • Set to 0 to disable caching.
  • ODP SegmentsCache timeout (in seconds) –itemTimeout
    • Default – 600 secs (10 minutes)
    • Set to 0 to disable timeout (never expires).
  • ODP enableasEnabled
    • Default – true (enabled)
    • The C# SDK returns or logs anodpNotEnabled error when ODP is disabled and its features are requested.

SeeCustomize OdpEventManager.

OdpSegmentManager

This module provides an interface to the remote Optimizely Data Platform (ODP) server for audience mappings.

It fetches qualified audiences for the given user context and returns them as a string array in the completion handler.

It also manages a segment's cache shared for all user contexts. The cache is in memory (not persistent), and a device reboot or app termination resets it.

OdpEventManager

This module provides an interface to the remote ODP server for events.

It queues pending events (persistent) and sends them (in batches of up to 10) to the ODP server when resources are available, including network connection and ODP public key (in the SDK's datafile).

📘

Note

The C# SDK tries to dispatch all events (stored in a persistent queue and retried on recoverable errors) but does not guarantee completion.

using OptimizelySDK.ErrorHandler;using OptimizelySDK.Logger;using OptimizelySDK.Odp;var logger = new DefaultLogger();var errorHandler = new DefaultErrorHandler();var httpClient = new HttpClient(); // or your own implementation of HttpClientvar segmentApiManager = new OdpSegmentApiManager(logger, errorHandler, httpClient);var segmentManager = new OdpSegmentManager(    segmentApiManager,    cacheSize: 10_000, // default is 10_000    itemTimeout: TimeSpan.FromMinutes(10), // default is 10 minutes    logger);var eventManager = new OdpEventManager.Builder().WithLogger(logger)    .WithErrorHandler(errorHandler) // Optional. Optimizely suggest a BlockingCollection or your own thread-safe collection // .WithEventQueue(new BlockingCollection<object>(10_000)) // Optional. If you choose to control the httpClient, you must also implement your own // .WithOdpEventApiManager(new OdpEventApiManager(logger, errorHandler, httpClient))    .Build();var odpManager = new OdpManager.Builder()    .WithSegmentManager(segmentManager)    .WithEventManager(eventManager)    .WithLogger(logger)    .WithErrorHandler(errorHandler)    .Build();

Customize OdpSegmentApiManager

When provided,OdpSegmentApiManager enables customization.

using OptimizelySDK.ErrorHandler;using OptimizelySDK.Logger;using OptimizelySDK.Odp;var logger = new DefaultLogger();var errorHandler = new DefaultErrorHandler();var yourCustomHttpClient = new HttpClient();var segmentApiManager = new OdpSegmentApiManager(logger, errorHandler, yourCustomHttpClient);

Customize OdpSegmentManager

You can provide your customizedOdpSegmentApiManager to theOdpSegmentManager along with different values for cache size and item timeouts.

// Continuing from above.var segmentManager = new OdpSegmentManager(    apiManager: segmentApiManager,    cacheSize: Constants.DEFAULT_MAX_CACHE_SIZE,    itemTimeout: TimeSpan.FromSeconds(Constants.DEFAULT_CACHE_SECONDS),    logger: logger);

Custom cache

You can use a custom caching mechanism for theOdpSegmentManager to store theFetchQualifiedSegments results. You must implement theICache interface or useLruCache to provide a custom cache.

// Continuing from above.var segmentApiManager = new OdpSegmentApiManager(logger, errorHandler, yourCustomHttpClient);var yourCustomSegmentCache = new LruCache<List<string>>();var segmentManager = new OdpSegmentManager(    apiManager: segmentApiManager,     cache: yourCustomSegmentCache,     logger: logger);

Customize OdpEventApiManager

When created,OdpEventApiManager enables customization.

// Continuing from above.var eventApiManager = new OdpEventApiManager(logger, errorHandler, yourCustomHttpClient);

Customize OdpEventManager

You can provide your customized Event API Manager to theOdpEventManager and adjust the flush interval, timeout interval, and auto-starting queue processing.

// Continuing from above.var yourCustomEventQueue = new BlockingCollection<object>(Constants.DEFAULT_QUEUE_CAPACITY);var eventManager = new OdpEventManager.Builder()    .WithEventQueue(yourCustomEventQueue)    .WithOdpEventApiManager(eventApiManager)    .WithFlushInterval(TimeSpan.FromMinutes(3))    .WithTimeoutInterval(TimeSpan.FromSeconds(5))    .WithAutoStart(true)    .WithLogger(logger)    .WithErrorHandler(errorHandler)    .Build();

Source files

The language and platform source files containing the implementation for C# are available onGitHub.

Updated 18 days ago



[8]ページ先頭

©2009-2025 Movatter.jp