.NET
The Unleash .NET SDK lets you evaluate feature flags in .NET applications. It connects to Unleash or Unleash Edge to fetch flag configurations and evaluates them locally against an Unleash context.
You can use this SDK with Unleash Enterprise or Unleash Open Source.
For an overview of how Unleash SDKs work, including offline behavior, feature compatibility across SDKs, and default refresh and metrics intervals, refer to the SDK overview.
Requirements
- .NET 6 and above
- .NET Standard 2.0
- .NET Framework 4.7 and above
Installation
Install the latest version of Unleash.Client from nuget.org or use the dotnet cli:
Initialization
In almost every case, you only want a single, shared instance of the Unleash client (a singleton) in your application. You would typically use a dependency injection framework to inject it where you need it. Having multiple instances of the client in your application could lead to inconsistencies and performance degradation.
To create a new instance of Unleash you need to create and pass in an UnleashSettings object.
The SDK synchronizes with the Unleash API on initialization. By default this happens asynchronously in the background. If you need to block until the SDK has synchronized, use synchronous startup.
When your application shuts down, remember to dispose the unleash instance.
Synchronous startup
This unleash client does not throw any exceptions if the unleash server is unreachable. Also, fetching features will return the default value if the feature toggle cache has not yet been populated. In many situations it is perferable to throw an error than allow an application to startup with incorrect feature toggle values. For these cases, we provide a client factory with the option for synchronous initialization.
The CreateClientAsync method was introduced in version 1.5.0, making the previous Generate method obsolete. There’s also a CreateClient method available if you don’t prefer the async version.
Project-scoped Unleash client
If you’re organizing your feature flags in projects in Unleash Enterprise, you can scope your API tokens to include only the specific projects needed for your client. Then use that token when configuring the Unleash client:
Check flags
The IsEnabled method allows you to check whether a feature is enabled:
If the Unleash client can’t find the feature you’re trying to check, it will default to returning false. You can change this behavior on a per-invocation basis by providing a fallback value as a second argument.
For instance, unleash.IsEnabled("SuperAwesomeFeature") would return false if SuperAwesomeFeature doesn’t exist. But if you’d rather it returned true, then you could pass that as the second argument:
You can also pass an Unleash context to evaluate flags for a specific user, session, or other properties required by strategies, constraints, and stickiness. Refer to the Unleash context section for details.
Events
Currently supported events:
- Impression data events
- Error events
- Toggles updated event
Activation strategies
The .NET client comes with implementations for the built-in activation strategies provided by unleash.
- DefaultStrategy
- UserWithIdStrategy
- GradualRolloutRandomStrategy
- GradualRolloutUserWithIdStrategy
- GradualRolloutSessionIdStrategy
- RemoteAddressStrategy
- ApplicationHostnameStrategy
- FlexibleRolloutStrategy
Read more about the strategies in the activation strategy reference docs.
Custom strategies
You can also specify and implement your own custom strategies. The specification must be registered in the Unleash UI and you must register the strategy implementation when you wire up unleash.
Unleash context
In order to use some of the common activation strategies you must provide an Unleash context.
If you have configured custom stickiness and want to use that with the FlexibleRolloutStrategy or Variants, add the custom stickiness parameters to the Properties dictionary on the Unleash Context:
UnleashContextProvider
The provider typically binds the context to the same thread as the request. If you are using Asp.Net the UnleashContextProvider will typically be a ‘request scoped’ instance.
Custom HTTP headers
If you want the client to send custom HTTP Headers with all requests to the Unleash api you can define that by setting them via the UnleashSettings.
Custom HttpClient initialization
If you need to specify HttpMessageHandlers or to control the instantiation of the HttpClient, you can create a custom HttpClientFactory that inherits from DefaultHttpClientFactory, and override the method CreateHttpClientInstance. Then configure UnleashSettings to use your custom HttpClientFactory.
Dynamic custom HTTP headers
If you need custom http headers that change during the lifetime of the client, a provider can be defined via the UnleashSettings.
Logging
By default Unleash-client uses LibLog to integrate with the currently configured logger for your application. The supported loggers are:
- Serilog
- NLog
- Log4Net
- EntLib
- Loupe
Custom logger integration
To plug in your own logger you can implement the ILogProvider interface, and register it with Unleash:
The GetLogger method is responsible for returning a delegate to be used for logging, and your logging integration should be placed inside that delegate:
Local caching and offline behavior
By default unleash-client fetches the feature flags from unleash-server every 20s, and stores the result in temporary .json file which is located in System.IO.Path.GetTempPath() directory. This means that if the unleash-server becomes unavailable, the unleash-client will still be able to toggle the features based on the values stored in .json file. As a result of this, the second argument of IsEnabled will be returned in two cases:
- When .json file does not exists
- When the named feature toggle does not exist in .json file
The backup file name will follow this pattern: {fileNameWithoutExtension}-{AppName}-{InstanceTag}-{SdkVersion}.{extension}, where InstanceTag is either what you configure on UnleashSettings during startup, or a formatted string with a random component following this pattern: {Dns.GetHostName()}-generated-{Guid.NewGuid()}.
You can configure InstanceTag like this:
Bootstrap
You can bootstrap the SDK with flag configuration to evaluate flags before connecting to Unleash. This is useful for applications deployed to ephemeral containers or environments where writing a local backup file is not possible.
By default, bootstrap data overrides any locally cached data. Set BootstrapOverride to false to keep cached data when available.
You can implement a custom provider using the IToggleBootstrapProvider interface, or use one of the built-in providers from Unleash.Utilities. Example bootstrap files are available in tests/Unleash.Tests/App_Data.
Custom provider
File
URL
Implement IToggleBootstrapProvider and pass it to ToggleBootstrapProvider:
Unit testing
You may want to mock the IUnleash interface in your unit tests. The SDK comes with a FakeUnleash implementation that you can use for this purpose.
Example usage:
Migrating to v5
If you use bootstrapping, custom strategies, or a custom JSON serializer, read the complete v5 migration guide before upgrading.