Defra.Livestock.Sdk.FeatureFlags 0.1.0

Prefix Reserved
dotnet add package Defra.Livestock.Sdk.FeatureFlags --version 0.1.0
                    
NuGet\Install-Package Defra.Livestock.Sdk.FeatureFlags -Version 0.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Defra.Livestock.Sdk.FeatureFlags" Version="0.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Defra.Livestock.Sdk.FeatureFlags" Version="0.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Defra.Livestock.Sdk.FeatureFlags" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Defra.Livestock.Sdk.FeatureFlags --version 0.1.0
                    
#r "nuget: Defra.Livestock.Sdk.FeatureFlags, 0.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Defra.Livestock.Sdk.FeatureFlags@0.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Defra.Livestock.Sdk.FeatureFlags&version=0.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Defra.Livestock.Sdk.FeatureFlags&version=0.1.0
                    
Install as a Cake Tool

lis-sdk-nuget-feature-flags

Part of the Livestock Information Service (LIS), which lets livestock keepers, owners, agents and delegates record and manage their animals.

Defra.Livestock.Sdk.FeatureFlags is a shared NuGet package that connects to the feature flag REST API to retrieve feature flag and feature flag group statuses for a given product and environment. Results are cached in memory.

Used by: LIS .NET services that need to evaluate feature flags.

Installation

dotnet add package Defra.Livestock.Sdk.FeatureFlags

The project produces the Defra.Livestock.Sdk.FeatureFlags package and targets net10.0. Its runtime dependencies are Microsoft.Extensions.Caching.Memory, Microsoft.Extensions.DependencyInjection.Abstractions, Microsoft.Extensions.Http, Microsoft.Extensions.Logging.Abstractions and Microsoft.Extensions.Options. Publishing is configured in the tag-triggered workflow and composite NuGet action.

Usage

Registration

Register the services in your IServiceCollection with AddFeatureFlags:

using Defra.Livestock.Sdk.FeatureFlags;

builder.Services.AddFeatureFlags(options =>
{
    options.BaseUrl = "https://feature-flag-url.com";
    options.ApiKey = "your-api-key";
    options.ProductName = "YourProductName";
    options.EnvironmentName = "dev";
    options.CacheTimeoutSeconds = 1800; // Optional
    options.WithCorrelationId(() => correlationIdProvider.Get()); // Optional
});

AddFeatureFlags registers the options (validated on start), an in-memory cache, a typed HttpClient and IFeatureFlagService.

Configuration options (Defra.Livestock.Sdk.FeatureFlags.Configuration.FeatureFlagOptions)

Property / method Type Description Required Validation
BaseUrl string Base URL of the feature flag API Yes Absolute URL, at most 2000 characters
ApiKey string API key, sent as x-api-key Yes At most 100 characters
ProductName string Product to evaluate flags for, sent as product-name Yes At most 50 characters
EnvironmentName string Environment to evaluate flags for (for example dev, test, ext-test, prod), sent as environment-name Yes At most 10 characters
CacheTimeoutSeconds int How long flag values are cached No (default 1800) 30 to 86400
WithCorrelationId() Func<Guid> Factory for the correlation ID sent as x-cdp-request-id. When not set, a new GUID is generated per request No Must not return Guid.Empty

Invalid options fail with an OptionsValidationException when the host starts.

Evaluating flags (Defra.Livestock.Sdk.FeatureFlags.IFeatureFlagService)

using Defra.Livestock.Sdk.FeatureFlags;

public class MyService(IFeatureFlagService featureFlagService)
{
    public async Task DoWorkAsync(CancellationToken cancellationToken)
    {
        // Check a single feature flag
        var flag = await featureFlagService.GetFeatureFlagStatusAsync("MyGroup", "MyFlag", cancellationToken);

        if (flag.FlagEnabled)
        {
            // Execute new feature logic
        }

        // Check a whole group of flags
        var group = await featureFlagService.GetFeatureFlagGroupStatusAsync("MyGroup", cancellationToken);

        if (group.GroupEnabled)
        {
            foreach (var feature in group.Features)
            {
                Console.WriteLine($"Flag: {feature.FlagName}, Enabled: {feature.FlagEnabled}");
            }
        }
    }
}

Group names are required and must be at most 100 characters; flag names are required.

Caching

Results are held in the registered IMemoryCache for CacheTimeoutSeconds, keyed by product, environment, group and (for single flags) flag name. Group and single-flag lookups are cached separately, so a cached group does not satisfy a single-flag request. Failures are not cached: the next call retries the API. The cache is per process, so each instance of a service queries the API independently.

Response models (Defra.Livestock.Sdk.FeatureFlags.Models)

FeatureFlagStatus is returned for a single flag, and for each flag in a group:

Property Type Meaning
FlagName string Name of the flag
FlagEnabled bool Whether the flag is enabled
Success bool Whether the flag was retrieved successfully

FeatureFlagGroupStatus is returned for a group:

Property Type Meaning
GroupName string Name of the group
GroupEnabled bool Whether the group is enabled
Features IReadOnlyList<FeatureFlagStatus> Statuses of the flags in the group; each has Success set to true
Success bool Whether the group was retrieved successfully

Exceptions (Defra.Livestock.Sdk.FeatureFlags.Exceptions)

Type Thrown when
FeatureFlagParameterException A group or flag name is invalid, or the correlation ID factory returns Guid.Empty
FeatureFlagQueryException The feature flag API cannot be reached, returns an error status, or its response cannot be processed

Logging

The SDK logs each request to the feature flag API through the ILogger registered in the DI container, at Information level. It does not log failures: callers are expected to log any exception they catch, which avoids logging the same error twice.

Prerequisites

  • .NET 10 SDK (the project targets net10.0). SDK selection and the Microsoft Testing Platform runner are configured in global.json.
  • To try a change in a consuming service: a local clone of lis-dev, which runs a local NuGet server

Setup

Development

dotnet restore FeatureFlags.slnx
dotnet build FeatureFlags.slnx

Running in development

This is a library, so it has no service of its own. To try a change in a consuming service before publishing, pack it and push it to the local NuGet server that lis-dev runs on port 5555 (nuget-server in its compose stack, already listed in lis-dev's nuget.config):

dotnet pack src/FeatureFlags/FeatureFlags.csproj -c Release -o ./artifacts /p:Version=0.0.0-local.1
dotnet nuget push "./artifacts/*.nupkg" --source http://localhost:5555/v3/index.json --api-key LOCAL-NUGET-API-KEY

Then reference that version from the consuming service.

Running tests

Tests use xUnit v3 with Shouldly assertions, NSubstitute mocks and Microsoft Testing Platform. Coverage includes the service, caching, HTTP client, mapping, validation and DI registration.

Run the tests through Microsoft Testing Platform:

dotnet test --solution FeatureFlags.slnx

Or run the xUnit test executable directly after building:

dotnet build tests/FeatureFlags.Tests/FeatureFlags.Tests.csproj
dotnet tests/FeatureFlags.Tests/bin/Debug/net10.0/Defra.Livestock.Sdk.FeatureFlags.Tests.dll

Pipelines

GitHub Actions use the composite actions under actions/ in DEFRA/lis-github-actions. Every workflow pins these actions to the v0.11.0 release commit (5f5557f64c1344efb6ed44e482452f9cfe6bea51). Update all uses: references together when moving to a newer release.

Workflow Trigger Configured behaviour
Prerelease Push to feature/** or hotfix/** Calculate a prerelease version, validate and run Sonar analysis, then tag the commit when validation succeeds and the quality gate passes
Pull Request Validation Pull request opened, updated or reopened against main Calculate a prospective version, validate and run Sonar analysis; aggregate the job results into a required check
Release Pull request merged into main Calculate a stable version, validate and run Sonar analysis, then tag the merged commit when validation succeeds and the quality gate passes
Publish Push of a tag matching *.*.* Run the central composite NuGet publishing action in a local job

NuGet's trusted publishing policy must use repository owner DEFRA, repository lis-sdk-nuget-feature-flags, workflow filename publish.yml, and environment release. The NUGET_USERNAME secret identifies the policy creator. The publishing job stays in this repository because NuGet rejects authentication inside a reusable workflow hosted in another repository.

Publishing requires an artifact built from the tagged commit by a successful prerelease or release workflow. The artifact records its commit, version, workflow run and attempt; publishing waits for that attempt to finish successfully before authenticating with NuGet.

Dependabot branches receive patch versions. Their PR validation versions use the label dependabot-alpha.<run>.<attempt>; feature and hotfix prereleases require an LREG ticket.

Branching policy

The repo uses mainline development. Branch from main and name the branch:

  • feature/LREG-<ticket>-<short-kebab-description>
  • hotfix/LREG-<ticket>-<short-kebab-description>

LREG must be uppercase, because the GitHub ruleset rejects other branch names. Rebase onto main rather than merging main in.

Contributing to this project

  • Follow the Defra software development standards.
  • Code style is configured in .editorconfig and stylecop.json, with StyleCop and .NET analyzers enabled during builds. Warnings are treated as errors. Save files as UTF-8 without a BOM, with LF line endings. Every .cs file needs the Defra copyright header (SA1633); .editorconfig supplies the template so IDEs add it automatically. Run dotnet format FeatureFlags.slnx --verify-no-changes to check formatting locally.
  • Open a pull request against main. CI must pass and the Sonar quality gate must be green before merge.

Licence

THIS INFORMATION IS LICENSED UNDER THE CONDITIONS OF THE OPEN GOVERNMENT LICENCE found at:

http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3

The following attribution statement MUST be cited in your products and applications when using this information.

Contains public sector information licensed under the Open Government licence v3

About the licence

The Open Government Licence (OGL) was developed by the Controller of His Majesty's Stationery Office (HMSO) to enable information providers in the public sector to license the use and re-use of their information under a common open licence.

It is designed to encourage use and re-use of information freely and flexibly, with only a few conditions.

Maintaining code analysis and public APIs

The build runs the .NET 10 recommended analyzer rules, StyleCop and SonarAnalyzer. Tests also receive xUnit analyzers through xunit.v3. Analyzer warnings are treated as errors; CA1707 is disabled for test code to allow descriptive names with underscores, and the test project also suppresses CS1591, CA2201 and CA1873 (see tests/FeatureFlags.Tests/Directory.Build.props).

The library uses Microsoft.CodeAnalysis.PublicApiAnalyzers to track its public surface, including nullability and default parameter values. These files make API changes visible during review and help catch accidental changes to the contract used by consuming services.

Every merged PR to main enters the release pipeline, so there is no separate release preparation step. Update src/FeatureFlags/PublicAPI.Shipped.txt in the same PR as the API change: it records the API contract that will be released on merge. Include both new types and their public members. The RS0016 code fix can generate declarations in src/FeatureFlags/PublicAPI.Unshipped.txt; move those additions into the shipped file before merging.

Keep PublicAPI.Unshipped.txt empty apart from #nullable enable unless it contains intentional *REMOVED* entries. Retain #nullable enable at the top of both files. Preserve previously shipped declarations as the compatibility record, and represent intentional removals using *REMOVED* entries in the unshipped file. Review breaking changes explicitly, since consuming services can still depend on earlier package versions.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0 25 12/2/2026
0.1.0-LREG-999-alpha.6.1 29 12/2/2026
0.1.0-LREG-999-alpha.2.1 46 12/1/2026