This document was generated from README.md in the .NET GitHub repository.
To connect to Unleash, you'll need your Unleash API url (e.g. https://<your-unleash>/api
) and a server-side API token (how do I create an API token?).
Unleash FeatureToggle Client for .Net
Migrating to v5
If you use bootstrapping, custom strategies, or a custom JSON serializer, read the complete migration guide before upgrading to v5.
Introduction
Unleash Client SDK for .Net. It is compatible with the Unleash-hosted.com SaaS offering and Unleash Open-Source.
The main motivation for doing feature toggling is to decouple the process for deploying code to production and releasing new features. This helps reducing risk, and allow us to easily manage which features to enable.
Feature toggles decouple deployment of code from release of new features.
Take a look at the demonstration site at unleash.herokuapp.com
Read more of the main project at github.com/unleash/unleash
Features
Supported Frameworks
- .Net 6
- NET Standard 2.0
- .Net 4.8
- .Net 4.7.2
- .Net 4.7
- .Net 4.6.1
- .Net 4.6
- .Net 4.5.1
- .Net 4.5
Extendable architecture
- Inject your own implementations of key components (background task scheduler, http client factory)
Getting started
Install the package
Install the latest version of Unleash.Client
from nuget.org or use the dotnet
cli:
dotnet add package unleash.client
Create a new a Unleash instance
⚠️ Important: 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.
If you create more than 10 instances, Unleash will attempt to log warnings about your usage.
To create a new instance of Unleash you need to create and pass in an UnleashSettings
object.
When creating an instance of the Unleash client, you can choose to do it either synchronously or asynchronously. The SDK will synchronize with the Unleash API on initialization, so it can take a moment for the it to reach the correct state. With an asynchronous startup, this would happen in the background while the rest of your code keeps executing. In most cases, this isn't an issue. But if you want to wait until the SDK is fully synchronized, then you should use the configuration explained in the synchronous startup section. This is usually not an issue and Unleash will do this in the background as soon as you initialize it. However, if it's important that you do not continue execution until the SDK has synchronized, then you should use the configuration explained in the synchronous startup section.
using Unleash;
var settings = new UnleashSettings()
{
AppName = "dotnet-test",
UnleashApi = new Uri("<your-api-url>"),
CustomHttpHeaders = new Dictionary<string, string>()
{
{"Authorization","<your-api-token>" }
}
};
var unleash = new DefaultUnleash(settings);
// Add to Container as Singleton
// .NET Core 3/.NET 5/...
services.AddSingleton<IUnleash>(c => unleash);
When your application shuts down, remember to dispose the unleash instance.
unleash?.Dispose()
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.
using Unleash;
using Unleash.ClientFactory;
var settings = new UnleashSettings()
{
AppName = "dotnet-test",
UnleashApi = new Uri("<your-api-url>"),
CustomHttpHeaders = new Dictionary<string, string>()
{
{"Authorization","<your-api-token>" }
}
};
var unleashFactory = new UnleashClientFactory();
IUnleash unleash = await unleashFactory.CreateClientAsync(settings, synchronousInitialization: true);
// this `unleash` has successfully fetched feature toggles and written them to its cache.
// if network errors or disk permissions prevented this from happening, the above await would have thrown an exception
var awesome = unleash.IsEnabled("SuperAwesomeFeature");
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 toggles 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:
var settings = new UnleashSettings()
{
AppName = "dotnet-test",
UnleashApi = new Uri("http://unleash.herokuapp.com/api/"),
CustomHttpHeaders = new Dictionary<string, string>()
{
{"Authorization","<your-project-scoped-api-token>" }
}
};
Check feature toggles
The IsEnabled
method allows you to check whether a feature is enabled:
if(unleash.IsEnabled("SuperAwesomeFeature"))
{
//do some magic
}
else
{
//do old boring stuff
}
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:
unleash.IsEnabled("SuperAwesomeFeature", true)
Providing context
You can also provide an Unleash context to the IsEnabled
method:
var context = new UnleashContext
{
UserId = "61"
};
unleash.IsEnabled("someToggle", context);
Refer to the Unleash context section for more information about using the Unleash context in the .NET SDK.
Handling events
Currently supported events:
- Impression data events
- Error events
- Toggles updated event
var settings = new UnleashSettings()
{
// ...
};
var unleash = new DefaultUnleash(settings);
// Set up handling of impression and error events
unleash.ConfigureEvents(cfg =>
{
cfg.ImpressionEvent = evt => { Console.WriteLine($"{evt.FeatureName}: {evt.Enabled}"); };
cfg.ErrorEvent = evt => { /* Handling code here */ Console.WriteLine($"{evt.ErrorType} occured."); };
cfg.TogglesUpdatedEvent = evt => { /* Handling code here */ Console.WriteLine($"Toggles updated on: {evt.UpdatedOn}"); };
});
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.
IStrategy s1 = new MyAwesomeStrategy();
IStrategy s2 = new MySuperAwesomeStrategy();
IUnleash unleash = new DefaultUnleash(config, s1, s2);