Defra.Livestock.Sdk.Strategies 0.3.0

Prefix Reserved
dotnet add package Defra.Livestock.Sdk.Strategies --version 0.3.0
                    
NuGet\Install-Package Defra.Livestock.Sdk.Strategies -Version 0.3.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.Strategies" Version="0.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Defra.Livestock.Sdk.Strategies" Version="0.3.0" />
                    
Directory.Packages.props
<PackageReference Include="Defra.Livestock.Sdk.Strategies" />
                    
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.Strategies --version 0.3.0
                    
#r "nuget: Defra.Livestock.Sdk.Strategies, 0.3.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.Strategies@0.3.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.Strategies&version=0.3.0
                    
Install as a Cake Addin
#tool nuget:?package=Defra.Livestock.Sdk.Strategies&version=0.3.0
                    
Install as a Cake Tool

lis-sdk-nuget-strategies

Defra.Livestock.Sdk.Strategies is a .NET package for building service operations as fluent strategies: repository access, REST and SOAP calls, and circuit breakers. It is part of the Livestock Information Service (LIS), which lets livestock keepers, owners, agents and delegates record and manage their animals.

The package implements the contracts in Defra.Livestock.Sdk.Strategies.Abstractions and adds dependency injection registration, FluentValidation support and exception helpers.

Installation

dotnet add package Defra.Livestock.Sdk.Strategies

The package targets net10.0. It brings in the abstractions package, FluentValidation and Polly.

Getting started

Register the framework and a factory for each class that uses strategies:

using Defra.Livestock.Sdk.Strategies;

services.AddStrategyFramework();

services.AddRepoStrategyFactory<HoldingService>((factory, context) => factory
    .WithDefaultLogger(context.Logger)
    .WithDefaultOperatorContext(context.OperatorContext)
    .WithDefaultEntityDescription("Holding"));

Inject the factory, build a strategy for one operation, configure it and execute it:

using Defra.Livestock.Sdk.Strategies.Operations;
using Defra.Livestock.Sdk.Strategies.Repositories;
using Defra.Livestock.Sdk.Strategies.Requests;

public class Holding
{
    public Guid Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public bool IsClosed { get; set; }
}

public class RenameHolding : OperationById<Guid>
{
    public string Name { get; set; } = string.Empty;
}

public interface IHoldingRepository : IRepoGettable<Holding>, IRepoUpdatable<Holding>;

public class HoldingService(
    IRepoStrategyFactory<HoldingService> strategies,
    IHoldingRepository repository)
{
    public Task<Holding> Rename(RenameHolding request, CancellationToken cancellationToken) =>
        strategies
            .BuildUpdateStrategy<Holding>()
            .WithCancellationToken(cancellationToken)
            .WithActionDescription("Rename")
            .WithRepository(repository)
            .WithRequest(request)
            .WithEntityFilter(holding => holding.Id == request.Id)
            .WithBusinessRules(rules => rules.Add(holding => !holding.IsClosed, "Holding must be open"))
            .WithUpdate(holding => holding.Name = request.Name)
            .Execute();
}

TService (here HoldingService) is the class that uses the strategy, and sets the logger category.

Every strategy needs a logger, a cancellation token, an action description and a target description (the entity or API). Executing without one throws InvalidOperationException. Circuit breakers derive both descriptions from the circuit key.

Registration

AddStrategyFramework() registers everything in this table. You can also register each part separately.

Method Registers
AddStrategyOperatorContext() IOperatorContext, scoped
AddStrategyValidators() The validators in this package, not those in your own assemblies. PagedQueryValidator requires a page number of at least 1 and a page size of 1 to 500
AddCircuitBreakerPolicyFactory() ICircuitBreakerPolicyFactory, transient

Factories are registered separately and are transient:

Method Also registers, if missing
AddRepoStrategyFactory<TService>()
AddRestStrategyFactory<TService>() IRestHttpClient
AddSoapStrategyFactory<TService>() ISoapHttpClient
AddCircuitBreakerStrategyFactory<TService>() A singleton ResiliencePipelineRegistry<string>

Each factory method has overloads that set defaults at registration:

  • (factory, context) => ... gives access to context.Logger, context.OperatorContext and context.ServiceProvider.
  • <TService, TOptions> adds an IOptions<TOptions> argument.
  • The circuit breaker overloads can also take an ICircuitBreakerPolicyFactory, before any options. The TOptions overload always does.

These overloads need logging and an IOperatorContext to be registered. Without them, set defaults where the factory is injected.

using Defra.Livestock.Sdk.Strategies;

services.Configure<MovementApiOptions>(configuration.GetSection("MovementApi"));

services.AddRestStrategyFactory<MovementClient, MovementApiOptions>((factory, context, options) => factory
    .WithDefaultLogger(context.Logger)
    .WithDefaultOperatorContext(context.OperatorContext)
    .WithDefaultApiDescription("Movement API")
    .WithDefaultBaseUrl(options.Value.BaseUrl)
    .WithDefaultApiKey(options.Value.ApiKey)
    .WithDefaultTimeout(5_000));

services.AddCircuitBreakerStrategyFactory<MovementClient>((factory, context, policies) => factory
    .WithDefaultLogger(context.Logger)
    .WithDefaultCircuitKey("movement-api")
    .WithDefaultFailureRatio(0.5)
    .WithDefaultMinimumThroughput(10)
    .WithDefaultSamplingDuration(30_000)
    .WithDefaultPolicy(policies.CreateHttpPolicy()));

Options set on a strategy override single-value factory defaults. Circuit breaker exception rules and policies add to the defaults.

Operator context

IOperatorContext identifies who is performing the operation. Set it once per scope, for example in middleware, with SetOperatorByClaimsPrincipal(user) or SetAuthenticatedOperatorById(id). Setting it twice throws InvalidOperationException. A claims principal must have a ClaimTypes.NameIdentifier claim.

Common options

All strategies support these options:

Option Purpose
WithLogger, WithCancellationToken, WithActionDescription Logging and cancellation
WithOperatorContext Identify the current operator in logs
WithRequiresAuthenticatedOperator Throw UnauthorizedAccessException unless the operator is authenticated
WithRequestValidation Validate the request, and throw RequestValidationException if it is invalid
WithBeforeExecute, WithAfterExecute Run code before request validation, or after the operation succeeds
When Apply configuration conditionally, with an optional else branch. Factories support it too

FluentValidation

WithRequestValidation accepts a FluentValidation result directly. Import Defra.Livestock.Sdk.Strategies.Operations for the extension method:

using Defra.Livestock.Sdk.Strategies.Operations;
using Defra.Livestock.Sdk.Strategies.Repositories;
using FluentValidation;

public record CreateHolding(string Name);

public class HoldingCreator(
    IRepoStrategyFactory<HoldingCreator> strategies,
    IRepoCreatable<Holding> repository,
    IValidator<CreateHolding> validator)
{
    public Task<Holding> Create(CreateHolding request, CancellationToken cancellationToken) =>
        strategies
            .BuildCreateStrategy<Holding>()
            .WithCancellationToken(cancellationToken)
            .WithActionDescription("Create")
            .WithRepository(repository)
            .WithRequestValidation(() => validator.ValidateAsync(request, cancellationToken))
            .WithCreate(() => new Holding { Id = Guid.NewGuid(), Name = request.Name })
            .Execute();
}

Any failure makes the request invalid, including those with Warning or Info severity.

Repository strategies

Repositories implement only the capabilities they support:

Build method Repository must implement Required options, besides the repository
BuildCreateStrategy IRepoCreatable WithCreate
BuildGetStrategy IRepoGettable WithRequest, WithEntityFilter
BuildGetListStrategy IRepoListable WithEntityFilter
BuildGetPagedStrategy IRepoPageable WithRequest, WithEntityFilter
BuildUpdateStrategy IRepoGettable, IRepoUpdatable WithRequest, WithEntityFilter, WithUpdate
BuildUpsertStrategy IRepoGettable, IRepoCreatable, IRepoUpdatable WithRequest, WithEntityFilter, WithCreate, WithUpdate

Set the entity description with WithDefaultEntityDescription on the factory or WithEntityDescription on the strategy. Create and upsert support WithAfterCreate, update and upsert support WithAfterUpdate, and update supports WithBeforeUpdate.

Get and update throw EntityNotFoundException when the filter matches nothing.

Returning results

  • Execute() returns the entity, list or PagedEntities<TEntity>.
  • ExecuteAndMap(map) maps each entity.
  • ExecuteAndTransform(transform) converts the whole list or page (get-list and get-paged only).

Paged strategies take a PagedQuery request, which also sets the sort direction through OrderByDescending. Pass the ordering expression last:

using Defra.Livestock.Sdk.Strategies.Operations;
using Defra.Livestock.Sdk.Strategies.Repositories;
using Defra.Livestock.Sdk.Strategies.Requests.Pagination;
using Defra.Livestock.Sdk.Strategies.Responses.Pagination;

public record HoldingSummary(Guid Id, string Name);

public class HoldingSearch(
    IRepoStrategyFactory<HoldingSearch> strategies,
    IRepoPageable<Holding> repository)
{
    public Task<PagedResults<HoldingSummary>> GetOpen(PagedQuery query, CancellationToken cancellationToken) =>
        strategies
            .BuildGetPagedStrategy<Holding>()
            .WithCancellationToken(cancellationToken)
            .WithActionDescription("Search")
            .WithRepository(repository)
            .WithRequest(query)
            .WithEntityFilter(holding => !holding.IsClosed)
            .ExecuteAndMap(holding => new HoldingSummary(holding.Id, holding.Name), holding => holding.Name);
}

Rules

A rule passes when its predicate returns true. The first failure throws.

Option Available on Throws
WithReferenceRules Create, update, upsert ReferenceRuleException
WithExistenceRules Get, update, upsert ExistenceRuleException
WithConflictRules Update, upsert ConflictRuleException
WithBusinessRules Update, upsert BusinessRuleException

Reference rules check that a related entity exists, and run before the entity is loaded or created. The others check the loaded entity, in the order shown, so an upsert skips them when it creates.

.WithReferenceRules(rules => rules.Add(keepers, keeper => keeper.Id == request.KeeperId, "Keeper must exist"))
.WithConflictRules(rules => rules.Add(holding => holding.Version == request.Version, "Holding has changed"))

keepers is an IRepoGettable<Keeper>. You can also add reusable EntityPredicateRule<TEntity> and EntityReferenceRule<TEntity> objects.

REST strategies

using Defra.Livestock.Sdk.Strategies.Operations;

public record Movement(Guid Id, string Status);

public record CreateMovement(string AnimalTag, string Destination);

public class MovementClient(IRestStrategyFactory<MovementClient> rest)
{
    public Task<Movement> Create(CreateMovement request, CancellationToken cancellationToken) =>
        rest
            .BuildRestStrategy()
            .WithCancellationToken(cancellationToken)
            .WithActionDescription("Create movement")
            .WithPost()
            .WithResourceUrl("/api/v1/movements")
            .WithQueryParameter("validateOnly", "false")
            .WithPayload(request)
            .Execute<Movement>();
}

A base URL, API description and HTTP method are required. The HTTP methods are WithGet, WithPost, WithPut, WithPatch, WithDelete, WithHead and WithOptions.

Execute with Result
Execute<TResult>() The deserialized response
ExecuteAndTransform<TResponse, TResult>(transform) The deserialized response, converted
ExecuteWithoutResponse() Nothing. Use it for responses such as 204 No Content

JSON uses snake_case names and case-insensitive matching by default. Change this with WithJsonSerializerOptions or WithDefaultJsonSerializerOptions.

HTTP options

REST and SOAP strategies share these options. Each except WithHeader has a WithDefault... equivalent on the factory.

Option Purpose
WithApiDescription Name the API in logs
WithBaseUrl Set the base URL
WithApiKey Send an x-api-key header, optionally only when a condition is true
WithBasicAuth Send basic authentication credentials
WithHeader Add a header
WithMediaType Set the media type. REST defaults to application/json; SOAP has no default
WithTimeout Set the timeout, from 1 to 300,000 milliseconds. The default is .NET's
WithVerboseOutput Receive request details and payloads for debugging. These can include personal data

Keep API keys and passwords in configuration or a secret store, not in code.

SOAP strategies

using System.Xml.Linq;
using Defra.Livestock.Sdk.Strategies.Operations;

public class AnimalStatusRequest
{
    public string TagNumber { get; set; } = string.Empty;
}

public class AnimalStatusClient(ISoapStrategyFactory<AnimalStatusClient> soap)
{
    public Task<XElement> Get(string tagNumber, CancellationToken cancellationToken) =>
        soap
            .BuildSoapStrategy()
            .WithCancellationToken(cancellationToken)
            .WithActionDescription("Get animal status")
            .WithApiDescription("Animal status service")
            .WithBaseUrl("https://soap.example")
            .WithServiceUrl("ws/animals.asmx")
            .WithSoapAction("http://example.org/GetStatus")
            .WithMediaType("text/xml")
            .WithSchemas(schemas => schemas.Add("Schemas/AnimalStatusRequest.xsd"))
            .WithValidatePayloadSchema()
            .WithPayload(new AnimalStatusRequest { TagNumber = tagNumber })
            .Execute();
}

The base URL, service URL, SOAP action, media type, API description and payload are all required. The URLs are joined with a /, so leave it off the start of the service URL and the end of the base URL.

Option Purpose
WithPayload Set the body from an object, or from a function returning an object or XElement
WithPayloadTransformer, WithResponseTransformer Change the XML before it is sent, or before it is deserialized
WithSchemas Add XSD schemas from files or embedded resources
WithValidatePreTransformPayloadSchema, WithValidatePayloadSchema Validate the payload before or after the transformer, optionally from a named descendant element. Throws XmlSchemaValidationException if it is invalid
WithXmlDeclaration Include the XML declaration

The execute methods match REST, with two additions: Execute() returns the body content as an XElement, and ExecuteAndTransform can work on that XElement.

Circuit breakers

A circuit breaker stops calling a failing dependency for a while. It wraps any asynchronous action.

using Defra.Livestock.Sdk.Strategies.Operations;

public class MovementReader(
    IRestStrategyFactory<MovementReader> rest,
    ICircuitBreakerStrategyFactory<MovementReader> circuitBreakers)
{
    public Task<Movement> Get(Guid id, CancellationToken cancellationToken) =>
        circuitBreakers
            .BuildCircuitBreakerStrategy()
            .WithCancellationToken(cancellationToken)
            .WithCircuitKey("movement-api")
            .WithFailureRatio(0.5)
            .WithMinimumThroughput(10)
            .WithSamplingDuration(30_000)
            .WithDurationOfBreak(15_000)
            .WithAction(token => rest
                .BuildRestStrategy()
                .WithCancellationToken(token)
                .WithActionDescription("Get movement")
                .WithGet()
                .WithResourceUrl($"/api/v1/movements/{id}")
                .Execute<Movement>())
            .Execute<Movement>();
}

The example assumes both factories were registered with defaults, as in Registration.

Thresholds

A circuit key, an action and at least one threshold are required. A failure ratio also needs a minimum throughput and a sampling duration. Durations are in milliseconds.

Option Allowed values Default
WithConsecutiveFailureThreshold 1 or more failures None
WithFailureRatio 0.001 to 1.0 None
WithMinimumThroughput 2 or more calls None; required with a failure ratio
WithSamplingDuration 1 or more None; required with a failure ratio
WithDurationOfBreak 1 or more 30,000
  • Consecutive failures opens the circuit after that many failures in a row, in the order calls complete. Any other outcome resets the count.
  • Failure ratio opens the circuit when the sampling window has at least the minimum throughput and the proportion of failures reaches the ratio. The window is approximate: old calls can count for slightly longer than the sampling duration.

If you set both, either can open the circuit. A low minimum throughput can make the ratio open it before the consecutive threshold is reached.

After the break, the next call is a trial and others are rejected until it finishes. A failure or caller cancellation reopens the circuit; any other outcome closes it and clears the counts. A trial that never finishes blocks the circuit, so set a timeout on the action and pass it the cancellation token.

Shared state

Circuits are held in memory in each application instance. Strategies with the same key share a circuit, whatever type they return. Use different keys for operations that should fail independently, and keep the number of keys bounded.

The first strategy to run for a key sets the thresholds and timings. Later strategies with different values use the original ones, and the first mismatch logs a warning. Exception rules, result rules and callbacks belong to each strategy.

Callbacks

OnBreak, OnHalfOpen and OnReset run when the circuit opens, starts a trial and closes. The strategy whose call caused the change supplies the callback.

  • Callbacks can run after the request has finished, so do not capture request-scoped services.
  • Keep them quick. A stalled callback can delay trial calls indefinitely.
  • Do not use the same circuit inside its own callback. Direct use throws InvalidOperationException, and waiting on indirect use can deadlock.
  • Exceptions from callbacks are logged and do not affect the call.

What counts as a failure

By default every exception counts, except these:

  • StrategyPreConditionException and its derived types, such as validation and rule failures
  • ArgumentException, InvalidOperationException and UnauthorizedAccessException, and their derived types

Use WithHandledException to count only specific exceptions, WithExcludedException to ignore more, and WithHandledResult to treat a returned value as a failure. Exclusions take precedence.

An OperationCanceledException caused by the caller's own cancellation token does not count as a failure or run the fallback. It reaches the caller.

Policies package these rules for reuse. Apply them with WithPolicy or WithDefaultPolicy. CircuitBreakerHttpPolicy, also available from ICircuitBreakerPolicyFactory.CreateHttpPolicy(), counts network errors, timeouts, and HTTP 429 and 5xx responses from REST and SOAP strategies.

To write your own, implement ICircuitBreakerPolicy:

using System.Data.Common;
using Defra.Livestock.Sdk.Strategies.Operations.Resilience.CircuitBreaker;
using Defra.Livestock.Sdk.Strategies.Operations.Resilience.CircuitBreaker.Policies;

public class DatabaseCircuitBreakerPolicy : ICircuitBreakerPolicy
{
    public void Execute<TService>(ICircuitBreakerStrategy<TService> circuitBreakerStrategy)
        where TService : class
    {
        circuitBreakerStrategy
            .WithHandledException(exception => exception is DbException { IsTransient: true })
            .WithHandledException<TimeoutException>();
    }
}

Fallbacks

WithFallback supplies a result when the circuit is open or the action throws an exception that counts as a failure. Without a fallback, an open circuit throws CircuitBreakerOpenException and other exceptions are rethrown. Excluded exceptions always reach the caller.

Exceptions

The abstractions README lists the exceptions that strategies throw. This package adds helpers for inspecting them:

Helper Available on Purpose
IsCircuitBreakerOpen() Exception Finds a CircuitBreakerOpenException in the exception or its inner exceptions. No using is needed beyond System
StatusCode() HttpClientException The HTTP status code, if there was a response
IsNotFound(), IsConflict(), Is400RangeError(), Is500RangeError() and similar HttpClientException Check for a status code or range
IsNetworkError() HttpClientException The request failed without an HTTP status code

HttpClientException is the base type for the REST and SOAP request and response exceptions. Its helpers are in Defra.Livestock.Sdk.Strategies.Exceptions.

Development

You need the .NET 10 SDK; global.json sets the version.

Build and test

dotnet build Strategies.slnx
dotnet test --solution Strategies.slnx

Tests use xUnit v3 on Microsoft Testing Platform, with Shouldly and NSubstitute.

Try a change in a consuming service

Clone lis-dev and start nuget-server from its compose stack. It listens on port 5555 and is already listed in lis-dev's nuget.config. Then pack and push a local version:

dotnet pack src/Strategies/Strategies.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

Reference that version from the consuming service.

Code style

The build runs the .NET recommended analyzers, StyleCop and SonarAnalyzer, and treats warnings as errors. Check formatting with:

dotnet format Strategies.slnx --verify-no-changes

Rule suppressions are in the Directory.Build.props files and .editorconfig, with reasons given in the Directory.Build.props comments.

Public API changes

Microsoft.CodeAnalysis.PublicApiAnalyzers tracks the public surface, so that API changes are visible in review. Every merge to main enters the release pipeline, so update the API files in the same pull request as the code:

  • Additions: add the type and each public member to src/Strategies/PublicAPI.Shipped.txt. The RS0016 code fix writes them to PublicAPI.Unshipped.txt; move them across before merging.
  • Removals: keep the shipped entry and add a matching *REMOVED* entry to PublicAPI.Unshipped.txt.
  • Keep #nullable enable at the top of both files. Apart from that line and *REMOVED* entries, PublicAPI.Unshipped.txt should be empty.

Review breaking changes explicitly, because consuming services may depend on earlier versions.

Contributing

  1. Branch from main, using feature/LREG-<ticket>-<short-kebab-description> or hotfix/LREG-<ticket>-<short-kebab-description>. LREG must be uppercase, because the GitHub ruleset rejects other branch names.
  2. Follow the Defra software development standards.
  3. Rebase onto main rather than merging it in.
  4. Open a pull request against main. CI and the Sonar quality gate must pass before merge.

Pipelines and releases

Workflow Trigger Result
Prerelease Push to feature/** or hotfix/** Builds, tests, runs Sonar and tags a prerelease version
Pull Request Validation Pull request to main Builds, tests and runs Sonar as a required check
Release Pull request merged to main Builds, tests, runs Sonar and tags a stable version
Publish Push of a *.*.* tag Publishes the package to NuGet

Versions are calculated by the pipeline, and commits are tagged only when validation and the quality gate pass. Dependabot branches receive patch versions, and their pull request validation uses the label dependabot-alpha.<run>.<attempt>. Feature and hotfix prereleases require an LREG ticket.

Publishing uses the artifact built from the tagged commit by a successful prerelease or release run, and waits for that run to finish.

The workflows use composite actions from lis-github-actions, all pinned to the same release commit. Dependabot groups updates to them into one pull request. If you update them by hand, change every uses: reference together.

NuGet trusted publishing must be configured with:

Setting Value
Repository owner DEFRA
Repository lis-sdk-nuget-strategies
Workflow publish.yml
Environment release

The NUGET_USERNAME secret identifies the policy creator. The publishing job must stay in this repository, because NuGet rejects authentication from a reusable workflow hosted in another one.

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.

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.3.0 92 12/3/2026
0.3.0-LREG-999-alpha.9.1 46 12/3/2026