OpenFeature 2.1.0
Prefix Reserveddotnet add package OpenFeature --version 2.1.0
NuGet\Install-Package OpenFeature -Version 2.1.0
<PackageReference Include="OpenFeature" Version="2.1.0" />
paket add OpenFeature --version 2.1.0
#r "nuget: OpenFeature, 2.1.0"
// Install OpenFeature as a Cake Addin #addin nuget:?package=OpenFeature&version=2.1.0 // Install OpenFeature as a Cake Tool #tool nuget:?package=OpenFeature&version=2.1.0
.NET SDK
OpenFeature is an open specification that provides a vendor-agnostic, community-driven API for feature flagging that works with your favorite feature flag management tool or in-house solution.
🚀 Quick start
Requirements
- .NET 6+
- .NET Core 6+
- .NET Framework 4.6.2+
Note that the packages will aim to support all current .NET versions. Refer to the currently supported versions .NET and .NET Framework excluding .NET Framework 3.5
Install
Use the following to initialize your project:
dotnet new console
and install OpenFeature:
dotnet add package OpenFeature
Usage
public async Task Example()
{
// Register your feature flag provider
await Api.Instance.SetProviderAsync(new InMemoryProvider());
// Create a new client
FeatureClient client = Api.Instance.GetClient();
// Evaluate your feature flag
bool v2Enabled = await client.GetBooleanValueAsync("v2_enabled", false);
if ( v2Enabled )
{
//Do some work
}
}
🌟 Features
Status | Features | Description |
---|---|---|
✅ | Providers | Integrate with a commercial, open source, or in-house feature management tool. |
✅ | Targeting | Contextually-aware flag evaluation using evaluation context. |
✅ | Hooks | Add functionality to various stages of the flag evaluation life-cycle. |
✅ | Logging | Integrate with popular logging packages. |
✅ | Domains | Logically bind clients with providers. |
✅ | Eventing | React to state changes in the provider or flag management system. |
✅ | Shutdown | Gracefully clean up a provider during application shutdown. |
✅ | Extending | Extend OpenFeature with custom providers and hooks. |
🔬 | DependencyInjection | Integrate OpenFeature with .NET's dependency injection for streamlined provider setup. |
Implemented: ✅ | In-progress: ⚠️ | Not implemented yet: ❌ | Experimental: 🔬
Providers
Providers are an abstraction between a flag management system and the OpenFeature SDK. Here is a complete list of available providers.
If the provider you're looking for hasn't been created yet, see the develop a provider section to learn how to build it yourself.
Once you've added a provider as a dependency, it can be registered with OpenFeature like this:
await Api.Instance.SetProviderAsync(new MyProvider());
In some situations, it may be beneficial to register multiple providers in the same application. This is possible using domains, which is covered in more detail below.
Targeting
Sometimes, the value of a flag must consider some dynamic criteria about the application or user such as the user's location, IP, email address, or the server's location. In OpenFeature, we refer to this as targeting. If the flag management system you're using supports targeting, you can provide the input data using the evaluation context.
// set a value to the global context
EvaluationContextBuilder builder = EvaluationContext.Builder();
builder.Set("region", "us-east-1");
EvaluationContext apiCtx = builder.Build();
Api.Instance.SetContext(apiCtx);
// set a value to the client context
builder = EvaluationContext.Builder();
builder.Set("region", "us-east-1");
EvaluationContext clientCtx = builder.Build();
var client = Api.Instance.GetClient();
client.SetContext(clientCtx);
// set a value to the invocation context
builder = EvaluationContext.Builder();
builder.Set("region", "us-east-1");
EvaluationContext reqCtx = builder.Build();
bool flagValue = await client.GetBooleanValuAsync("some-flag", false, reqCtx);
Hooks
Hooks allow for custom logic to be added at well-defined points of the flag evaluation life-cycle. Look here for a complete list of available hooks. If the hook you're looking for hasn't been created yet, see the develop a hook section to learn how to build it yourself.
Once you've added a hook as a dependency, it can be registered at the global, client, or flag invocation level.
// add a hook globally, to run on all evaluations
Api.Instance.AddHooks(new ExampleGlobalHook());
// add a hook on this client, to run on all evaluations made by this client
var client = Api.Instance.GetClient();
client.AddHooks(new ExampleClientHook());
// add a hook for this evaluation only
var value = await client.GetBooleanValueAsync("boolFlag", false, context, new FlagEvaluationOptions(new ExampleInvocationHook()));
Logging
The .NET SDK uses Microsoft.Extensions.Logging. See the manual for complete documentation.
Domains
Clients can be assigned to a domain. A domain is a logical identifier which can be used to associate clients with a particular provider. If a domain has no associated provider, the default provider is used.
// registering the default provider
await Api.Instance.SetProviderAsync(new LocalProvider());
// registering a provider to a domain
await Api.Instance.SetProviderAsync("clientForCache", new CachedProvider());
// a client backed by default provider
FeatureClient clientDefault = Api.Instance.GetClient();
// a client backed by CachedProvider
FeatureClient scopedClient = Api.Instance.GetClient("clientForCache");
Domains can be defined on a provider during registration. For more details, please refer to the providers section.
Eventing
Events allow you to react to state changes in the provider or underlying flag management system, such as flag definition changes,
provider readiness, or error conditions.
Initialization events (PROVIDER_READY
on success, PROVIDER_ERROR
on failure) are dispatched for every provider.
Some providers support additional events, such as PROVIDER_CONFIGURATION_CHANGED
.
Please refer to the documentation of the provider you're using to see what events are supported.
Example usage of an Event handler:
public static void EventHandler(ProviderEventPayload eventDetails)
{
Console.WriteLine(eventDetails.Type);
}
EventHandlerDelegate callback = EventHandler;
// add an implementation of the EventHandlerDelegate for the PROVIDER_READY event
Api.Instance.AddHandler(ProviderEventTypes.ProviderReady, callback);
It is also possible to register an event handler for a specific client, as in the following example:
EventHandlerDelegate callback = EventHandler;
var myClient = Api.Instance.GetClient("my-client");
var provider = new ExampleProvider();
await Api.Instance.SetProviderAsync(myClient.GetMetadata().Name, provider);
myClient.AddHandler(ProviderEventTypes.ProviderReady, callback);
Shutdown
The OpenFeature API provides a close function to perform a cleanup of all registered providers. This should only be called when your application is in the process of shutting down.
// Shut down all providers
await Api.Instance.ShutdownAsync();
Extending
Develop a provider
To develop a provider, you need to create a new project and include the OpenFeature SDK as a dependency.
This can be a new repository or included in the existing contrib repository available under the OpenFeature organization.
You’ll then need to write the provider by implementing the FeatureProvider
interface exported by the OpenFeature SDK.
public class MyProvider : FeatureProvider
{
public override Metadata GetMetadata()
{
return new Metadata("My Provider");
}
public override Task<ResolutionDetails<bool>> ResolveBooleanValueAsync(string flagKey, bool defaultValue, EvaluationContext? context = null, CancellationToken cancellationToken = default)
{
// resolve a boolean flag value
}
public override Task<ResolutionDetails<string>> ResolveStringValueAsync(string flagKey, string defaultValue, EvaluationContext? context = null, CancellationToken cancellationToken = default)
{
// resolve a string flag value
}
public override Task<ResolutionDetails<int>> ResolveIntegerValueAsync(string flagKey, int defaultValue, EvaluationContext context = null)
{
// resolve an int flag value
}
public override Task<ResolutionDetails<double>> ResolveDoubleValueAsync(string flagKey, double defaultValue, EvaluationContext? context = null, CancellationToken cancellationToken = default)
{
// resolve a double flag value
}
public override Task<ResolutionDetails<Value>> ResolveStructureValueAsync(string flagKey, Value defaultValue, EvaluationContext? context = null, CancellationToken cancellationToken = default)
{
// resolve an object flag value
}
}
Develop a hook
To develop a hook, you need to create a new project and include the OpenFeature SDK as a dependency.
This can be a new repository or included in the existing contrib repository available under the OpenFeature organization.
Implement your own hook by conforming to the Hook interface
.
To satisfy the interface, all methods (Before
/After
/Finally
/Error
) need to be defined.
public class MyHook : Hook
{
public ValueTask<EvaluationContext> BeforeAsync<T>(HookContext<T> context,
IReadOnlyDictionary<string, object> hints = null)
{
// code to run before flag evaluation
}
public ValueTask AfterAsync<T>(HookContext<T> context, FlagEvaluationDetails<T> details,
IReadOnlyDictionary<string, object> hints = null)
{
// code to run after successful flag evaluation
}
public ValueTask ErrorAsync<T>(HookContext<T> context, Exception error,
IReadOnlyDictionary<string, object> hints = null)
{
// code to run if there's an error during before hooks or during flag evaluation
}
public ValueTask FinallyAsync<T>(HookContext<T> context, IReadOnlyDictionary<string, object> hints = null)
{
// code to run after all other stages, regardless of success/failure
}
}
Built a new hook? Let us know so we can add it to the docs!
DependencyInjection
[!NOTE] The OpenFeature.DependencyInjection and OpenFeature.Hosting packages are currently experimental. They streamline the integration of OpenFeature within .NET applications, allowing for seamless configuration and lifecycle management of feature flag providers using dependency injection and hosting services.
Installation
To set up dependency injection and hosting capabilities for OpenFeature, install the following packages:
dotnet add package OpenFeature.DependencyInjection
dotnet add package OpenFeature.Hosting
Usage Examples
For a basic configuration, you can use the InMemoryProvider. This provider is simple and well-suited for development and testing purposes.
Basic Configuration:
builder.Services.AddOpenFeature(featureBuilder => {
featureBuilder
.AddHostedFeatureLifecycle() // From Hosting package
.AddContext((contextBuilder, serviceProvider) => { /* Custom context configuration */ })
.AddInMemoryProvider();
});
Domain-Scoped Provider Configuration:
<br />To set up multiple providers with a selection policy, define logic for choosing the default provider. This example designates name1
as the default provider:
builder.Services.AddOpenFeature(featureBuilder => {
featureBuilder
.AddHostedFeatureLifecycle()
.AddContext((contextBuilder, serviceProvider) => { /* Custom context configuration */ })
.AddInMemoryProvider("name1")
.AddInMemoryProvider("name2")
.AddPolicyName(options => {
// Custom logic to select a default provider
options.DefaultNameSelector = serviceProvider => "name1";
});
});
Creating a New Provider
To integrate a custom provider, such as InMemoryProvider, you’ll need to create a factory that builds and configures the provider. This section demonstrates how to set up InMemoryProvider as a new provider with custom configuration options.
Configuring InMemoryProvider as a New Provider
<br />Begin by creating a custom factory class, InMemoryProviderFactory
, that implements IFeatureProviderFactory
. This factory will initialize your provider with any necessary configurations.
public class InMemoryProviderFactory : IFeatureProviderFactory
{
internal IDictionary<string, Flag>? Flags { get; set; }
public FeatureProvider Create() => new InMemoryProvider(Flags);
}
Adding an Extension Method to OpenFeatureBuilder
<br />To streamline the configuration process, add an extension method, AddInMemoryProvider
, to OpenFeatureBuilder
. This allows you to set up the provider with either a domain-scoped or a default configuration.
public static partial class FeatureBuilderExtensions
{
public static OpenFeatureBuilder AddInMemoryProvider(this OpenFeatureBuilder builder, Action<IDictionary<string, Flag>>? configure = null)
=> builder.AddProvider<InMemoryProviderFactory>(factory => ConfigureFlags(factory, configure));
public static OpenFeatureBuilder AddInMemoryProvider(this OpenFeatureBuilder builder, string domain, Action<IDictionary<string, Flag>>? configure = null)
=> builder.AddProvider<InMemoryProviderFactory>(domain, factory => ConfigureFlags(factory, configure));
private static void ConfigureFlags(InMemoryProviderFactory factory, Action<IDictionary<string, Flag>>? configure)
{
if (configure == null)
return;
var flag = new Dictionary<string, Flag>();
configure.Invoke(flag);
factory.Flags = flag;
}
}
⭐️ Support the project
- Give this repo a ⭐️!
- Follow us on social media:
- Twitter: @openfeature
- LinkedIn: OpenFeature
- Join us on Slack
- For more information, check out our community page
🤝 Contributing
Interested in contributing? Great, we'd love your help! To get started, take a look at the CONTRIBUTING guide.
Thanks to everyone who has already contributed
Made with contrib.rocks.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
.NET Framework | net461 was computed. net462 is compatible. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen40 was computed. tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETFramework 4.6.2
- Microsoft.Bcl.AsyncInterfaces (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.2)
- System.Collections.Immutable (>= 1.7.1)
- System.Threading.Channels (>= 6.0.0)
- System.ValueTuple (>= 4.5.0)
-
.NETStandard 2.0
- Microsoft.Bcl.AsyncInterfaces (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.2)
- System.Collections.Immutable (>= 1.7.1)
- System.Threading.Channels (>= 6.0.0)
-
net6.0
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.2)
-
net8.0
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.2)
NuGet packages (19)
Showing the top 5 NuGet packages that depend on OpenFeature:
Package | Downloads |
---|---|
DevCycle.SDK.Server.Common
Package Description |
|
LaunchDarkly.OpenFeature.ServerProvider
LaunchDarkly OpenFeature Provider for the Server-Side SDK for .NET |
|
CloudBees.OpenFeature.Provider
An OpenFeature provider for CloudBees Feature Management |
|
Octopus.OpenFeature
The OctopusDeploy dotnet OpenFeature provide |
|
OpenFeature.Contrib.Hooks.Otel
Open Telemetry Hook for .NET |
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated |
---|---|---|
2.1.0 | 2,957 | 11/18/2024 |
2.0.0 | 55,093 | 8/21/2024 |
1.6.0 | 83,631 | 7/29/2024 |
1.5.2 | 205 | 7/26/2024 |
1.5.1 | 105,687 | 4/9/2024 |
1.5.0 | 50,743 | 3/12/2024 |
1.4.1 | 63,354 | 1/23/2024 |
1.4.0 | 6,303 | 1/23/2024 |
1.3.1 | 683,529 | 9/19/2023 |
1.3.0 | 25,643 | 7/14/2023 |
1.2.0 | 103,243 | 2/14/2023 |
1.1.0 | 2,618 | 1/18/2023 |
1.0.1 | 11,039 | 10/28/2022 |
1.0.0 | 5,473 | 10/26/2022 |
0.5.0 | 6,007 | 10/16/2022 |
0.4.0 | 810 | 10/12/2022 |
0.3.0 | 1,291 | 9/29/2022 |
0.2.3 | 482 | 9/22/2022 |
0.1.5 | 564 | 9/19/2022 |
0.1.4 | 444 | 9/8/2022 |
0.1.3 | 438 | 8/25/2022 |
0.1.2 | 441 | 8/10/2022 |
0.1.1 | 459 | 7/18/2022 |
0.1.0 | 567 | 7/14/2022 |