Defra.Livestock.Sdk.Strategies.Abstractions 0.3.0

Prefix Reserved
dotnet add package Defra.Livestock.Sdk.Strategies.Abstractions --version 0.3.0
                    
NuGet\Install-Package Defra.Livestock.Sdk.Strategies.Abstractions -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.Abstractions" 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.Abstractions" Version="0.3.0" />
                    
Directory.Packages.props
<PackageReference Include="Defra.Livestock.Sdk.Strategies.Abstractions" />
                    
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.Abstractions --version 0.3.0
                    
#r "nuget: Defra.Livestock.Sdk.Strategies.Abstractions, 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.Abstractions@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.Abstractions&version=0.3.0
                    
Install as a Cake Addin
#tool nuget:?package=Defra.Livestock.Sdk.Strategies.Abstractions&version=0.3.0
                    
Install as a Cake Tool

lis-sdk-nuget-strategies-abstractions

Defra.Livestock.Sdk.Strategies.Abstractions is a .NET package of contracts 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 contains interfaces, simple models, exceptions and a few extension methods. The implementations are in Defra.Livestock.Sdk.Strategies. Reference this package on its own when a project needs the contracts but not the implementation.

Installation

dotnet add package Defra.Livestock.Sdk.Strategies.Abstractions

The package targets net10.0. Its only runtime dependency is Microsoft.Extensions.Logging.Abstractions.

There is nothing to configure or register for this package. To run strategies, register the implementations from Defra.Livestock.Sdk.Strategies.

Namespaces omit the .Abstractions suffix: types live under Defra.Livestock.Sdk.Strategies.

Usage

Inject a factory, set any defaults, build a strategy for one operation, configure it and execute it.

Factory Builds
IRepoStrategyFactory<TService> Create, update, upsert, get, get-list and get-paged repository strategies
IRestStrategyFactory<TService> IRestStrategy<TService>
ISoapStrategyFactory<TService> ISoapStrategy<TService>
ICircuitBreakerStrategyFactory<TService> ICircuitBreakerStrategy<TService>

TService is the class that uses the strategy, and sets the logger category. The factories are in Defra.Livestock.Sdk.Strategies.Operations.

Every strategy needs a logger, set with WithDefaultLogger on the factory or WithLogger on the strategy. All strategies support these options:

Option Purpose
WithLogger, WithCancellationToken, WithActionDescription Logging and cancellation
WithOperatorContext, WithRequiresAuthenticatedOperator Identify the current operator and require them to be authenticated
WithRequestValidation Validate the request
WithBeforeExecute, WithAfterExecute Run code before or after the operation
When Apply configuration conditionally, with an optional else branch

Repository operations

This service reads and updates an entity:

using Defra.Livestock.Sdk.Strategies.Operations;
using Defra.Livestock.Sdk.Strategies.Repositories;
using Defra.Livestock.Sdk.Strategies.Requests;
using Microsoft.Extensions.Logging;

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,
    ILogger<HoldingService> logger)
{
    public Task<Holding> Get(IOperationById<Guid> request, CancellationToken cancellationToken) =>
        strategies
            .WithDefaultLogger(logger)
            .WithDefaultEntityDescription("holding")
            .BuildGetStrategy<Holding>()
            .WithCancellationToken(cancellationToken)
            .WithRepository(repository)
            .WithRequest(request)
            .WithEntityFilter(holding => holding.Id == request.Id)
            .Execute();

    public Task<Holding> Rename(RenameHolding request, CancellationToken cancellationToken) =>
        strategies
            .WithDefaultLogger(logger)
            .WithDefaultEntityDescription("holding")
            .BuildUpdateStrategy<Holding>()
            .WithCancellationToken(cancellationToken)
            .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();
}

Repositories implement only the capabilities they support:

Strategy Repository must implement
Create IRepoCreatable<TEntity>
Get IRepoGettable<TEntity>
Get list IRepoListable<TEntity>
Get paged IRepoPageable<TEntity>
Update IRepoGettable<TEntity> and IRepoUpdatable<TEntity>
Upsert IRepoGettable<TEntity>, IRepoCreatable<TEntity> and IRepoUpdatable<TEntity>

Rules

Rules are added through a builder on the strategy, either inline or as reusable EntityPredicateRule<TEntity> and EntityReferenceRule<TEntity> objects.

Option Available on
WithExistenceRules Get, update, upsert
WithReferenceRules Create, update, upsert
WithConflictRules Update, upsert
WithBusinessRules Update, upsert

REST, SOAP and circuit breakers

This service makes a REST call inside a circuit breaker:

using Defra.Livestock.Sdk.Strategies.Exceptions;
using Defra.Livestock.Sdk.Strategies.Operations;

public record Movement(Guid Id);

public class MovementClient(
    IRestStrategyFactory<MovementClient> rest,
    ICircuitBreakerStrategyFactory<MovementClient> circuitBreakers)
{
    public Task<Movement> Get(Guid id, CancellationToken cancellationToken) =>
        circuitBreakers
            .BuildCircuitBreakerStrategy()
            .WithCancellationToken(cancellationToken)
            .WithCircuitKey("movements")
            .WithConsecutiveFailureThreshold(5)
            .WithDurationOfBreak(30_000) // milliseconds
            .WithHandledException<RestRequestException>()
            .WithAction(token => rest
                .BuildRestStrategy()
                .WithCancellationToken(token)
                .WithBaseUrl("https://movements.example")
                .WithResourceUrl($"/movements/{id}")
                .WithGet()
                .Execute<Movement>())
            .Execute<Movement>();
}

The example assumes both factories were registered with a default logger. REST and SOAP strategies share options for base URL, API key, basic authentication, headers, media type and timeout. SOAP strategies also support XSD schema validation and payload and response transformers.

Pagination

  • PagedQuery is the request model: PageNumber, PageSize, OrderBy and OrderByDescending. Pass it to a get-paged strategy with WithRequest.
  • QueryablePagingExtensions.ToPaged helps repositories implement IRepoPageable<TEntity>. It orders and pages an IQueryable<T> into PagedEntities<T>, and takes delegates for the async count and list calls so that the package does not depend on an ORM.
  • PagedEntitiesExtensions.ToPagedResults maps PagedEntities<T> to a PagedResults<T> response.

Supporting types

  • IOperatorContext exposes the current Operator: ID, name, email, roles and whether they are authenticated.
  • RequestValidationResult collects RequestValidationFailure entries. IsValid is true only when there are none, so a Warning or Info entry also makes a result invalid.
  • ExpressionExtensions.AndAlso combines two predicate expressions, for example to build an entity filter.

Exceptions

Calling services can catch these types and map them to HTTP responses. They are in Defra.Livestock.Sdk.Strategies.Exceptions, with base types in Exceptions.Base.

Type Base Meaning
RequestValidationException StrategyPreConditionException Request validation failed; see Errors
EntityNotFoundException StrategyPreConditionException The requested entity does not exist
ExistenceRuleException StrategyPreConditionException An existence rule failed
ReferenceRuleException StrategyPreConditionException A referenced entity does not exist
ConflictRuleException StrategyPreConditionException A conflict rule failed
BusinessRuleException StrategyPreConditionException A business rule failed
SoapSchemaBuilderException StrategyPreConditionException A SOAP schema could not be built
RestRequestException, SoapRequestException HttpClientException The request failed
RestResponseException, SoapResponseException HttpClientException The service returned an error, or a response without the required content
CircuitBreakerOpenException Exception The circuit is open, so the call was rejected

Development

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

Build and test

dotnet build Strategies.Abstractions.slnx
dotnet tests/Strategies.Tests/bin/Debug/net10.0/Defra.Livestock.Sdk.Strategies.Abstractions.Tests.dll

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.Abstractions.slnx --verify-no-changes

Rule suppressions are in the Directory.Build.props files and .editorconfig, most with a comment giving the reason.

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-abstractions
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 (1)

Showing the top 1 NuGet packages that depend on Defra.Livestock.Sdk.Strategies.Abstractions:

Package Downloads
Defra.Livestock.Sdk.Strategies

Implementation of the Livestock Information Service (LIS) strategies package: fluent strategy builders and factories for repository, REST, SOAP and circuit breaker operations, with business rule builders, request validation and dependency injection registration.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.3.0 103 12/3/2026
0.3.0-LREG-9999-alpha.7.1 42 12/3/2026
0.2.0 59 12/2/2026
0.2.0-LREG-999-alpha.6.1 38 12/2/2026