Innovabit.Architecture.Patterns 1.0.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package Innovabit.Architecture.Patterns --version 1.0.1
                    
NuGet\Install-Package Innovabit.Architecture.Patterns -Version 1.0.1
                    
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="Innovabit.Architecture.Patterns" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Innovabit.Architecture.Patterns" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="Innovabit.Architecture.Patterns" />
                    
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 Innovabit.Architecture.Patterns --version 1.0.1
                    
#r "nuget: Innovabit.Architecture.Patterns, 1.0.1"
                    
#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 Innovabit.Architecture.Patterns@1.0.1
                    
#: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=Innovabit.Architecture.Patterns&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=Innovabit.Architecture.Patterns&version=1.0.1
                    
Install as a Cake Tool

Innovabit.Architecture.Patterns — Strategy

Reusable, DI-friendly implementation of the Strategy pattern for .NET, with first-class support for dependency injection via Microsoft.Extensions.DependencyInjection, synchronous and asynchronous resolution, and CancellationToken propagation.

Instead of hardcoding if/else or switch statements to pick between multiple implementations of the same abstraction, this library lets you register any number of candidate implementations and delegate the selection logic to a resolver function you control (feature flags, environment, tenant configuration, A/B testing, etc.).

Table of contents

Why this package

Picking between implementations of an interface is a common problem: legacy vs. new service, canary rollout, per-tenant behavior, per-region behavior, etc. This is usually solved with either:

  • Scattered if (featureFlag) { ... } else { ... } blocks across the codebase, or
  • A hand-rolled factory class per use case, duplicated project after project.

This package gives you a single, generic, testable building block instead — register your candidates once, provide a resolver function, and inject StrategyResolver<TDefinition> wherever you need the resolved instance.

Installation

dotnet add package Innovabit.Architecture.Patterns

Core concepts

Type Responsibility
StrategyResolver<TDefinition> Holds the registered candidates and resolves one of them on demand (sync or async).
StrategyResolverFunc<T> Delegate:(StrategyResolverContext, IReadOnlyList<T>) => T. Your selection logic.
StrategyResolverAsyncFunc<T> Delegate:(StrategyResolverContext, IReadOnlyList<T>) => Task<T>. Async variant.
StrategyResolverContext Carries theIServiceProvider and a CancellationToken into your resolver function.
IStrategyBuilder<TDefinition> Fluent builder to register candidates and configure the resolver via DI.

Quick start

using Microsoft.Extensions.DependencyInjection;
using Innovabit.Architecture.Patterns.Behavioral.Strategy;

public interface IPaymentService
{
    Task ChargeAsync(decimal amount);
}

public class LegacyPaymentService : IPaymentService
{
    public Task ChargeAsync(decimal amount) => Task.CompletedTask;
}

public class NewPaymentService : IPaymentService
{
    public Task ChargeAsync(decimal amount) => Task.CompletedTask;
}

var services = new ServiceCollection();

services
    .AddStrategy<IPaymentService>((context, candidates) =>
        FeatureFlags.IsEnabled("new-payment-flow")
            ? candidates.OfType<NewPaymentService>().Single()
            : candidates.OfType<LegacyPaymentService>().Single())
    .AddCandidate<LegacyPaymentService>()
    .AddCandidate<NewPaymentService>()
    .Build();

var provider = services.BuildServiceProvider();
var resolver = provider.GetRequiredService<StrategyResolver<IPaymentService>>();

IPaymentService paymentService = resolver.Resolve();
await paymentService.ChargeAsync(99.99m);

AddCandidate<T>() also registers each candidate type in the DI container, so they get built with their own dependencies resolved as usual — no manual new calls needed.

Synchronous resolution

Use AddStrategy and resolver.Resolve() when your selection logic doesn't need I/O (e.g. an in-memory feature flag, a config value already loaded at startup):

services
    .AddStrategy<IPaymentService>((context, candidates) => candidates[0])
    .AddCandidate<LegacyPaymentService>()
    .Build();
var resolver = provider.GetRequiredService<StrategyResolver<IPaymentService>>();
var service = resolver.Resolve();

Calling Resolve() on a resolver configured with AddAsyncStrategy throws InvalidOperationException. This is intentional — it prevents accidentally blocking on async code (.Result / .GetAwaiter().GetResult()), a common source of deadlocks in ASP.NET.

Asynchronous resolution

Use AddAsyncStrategy and resolver.ResolveAsync() when your resolver function needs to call a remote service (e.g. a feature-flag provider, a database, a config service):

services
    .AddAsyncStrategy<IPaymentService>(async (context, candidates) =>
    {
        var flags = context.ServiceProvider.GetRequiredService<IFeatureFlagService>();
        var enabled = await flags.IsEnabledAsync("new-payment-flow", context.CancellationToken);
        return enabled
            ? candidates.OfType<NewPaymentService>().Single()
            : candidates.OfType<LegacyPaymentService>().Single();
    })
    .AddCandidate<LegacyPaymentService>()
    .AddCandidate<NewPaymentService>()
    .Build();
var resolver = provider.GetRequiredService<StrategyResolver<IPaymentService>>();
var service = await resolver.ResolveAsync(cancellationToken);

A resolver configured with AddStrategy (sync) can still be awaited via ResolveAsync() — it simply runs synchronously inside the Task, without blocking any thread. This means ResolveAsync() always works regardless of how the resolver was registered; only Resolve() is restricted to sync-only resolvers.

Registering a proxy implementation with WithImplementation

If you want consumers to depend directly on TDefinition (instead of resolving StrategyResolver<TDefinition> themselves), register a lightweight proxy that delegates to the resolver:

public class PaymentServiceProxy : IPaymentService
{
    private readonly StrategyResolver<IPaymentService> _resolver;

    public PaymentServiceProxy(StrategyResolver<IPaymentService> resolver) => _resolver = resolver;

    public Task ChargeAsync(decimal amount) => _resolver.Resolve().ChargeAsync(amount);
}
services
    .AddStrategy<IPaymentService>((context, candidates) => candidates[0])
    .AddCandidate<LegacyPaymentService>()
    .AddCandidate<NewPaymentService>()
    .WithImplementation<PaymentServiceProxy>()
    .Build();
// Consumers can now inject IPaymentService directly:
public class CheckoutController(IPaymentService paymentService)
{
    // paymentService is a PaymentServiceProxy under the hood
}

Safe registration with TryBuild

If candidate registration is conditional (e.g. driven by configuration) and you don't want the application to crash on startup when no candidates end up registered, use TryBuild instead of Build:

var builder = services.AddStrategy<IPaymentService>((context, candidates) => candidates[0]);

if (configuration.GetValue<bool>("Payments:EnableLegacy"))
{
    builder.AddCandidate<LegacyPaymentService>();
}

if (configuration.GetValue<bool>("Payments:EnableNew"))
{
    builder.AddCandidate<NewPaymentService>();
}

if (!builder.TryBuild(out _))
{
    logger.LogWarning("No payment candidates were registered; the payment strategy is disabled.");
}

Build() throws InvalidOperationException if no candidates were registered; TryBuild() returns false instead.

Controlling the service lifetime

By default, candidates and the resolver are registered as Scoped. Override it via the lifetime parameter:

services
    .AddStrategy<IPaymentService>(
        (context, candidates) => candidates[0],
        lifetime: ServiceLifetime.Singleton)
    .AddCandidate<LegacyPaymentService>()
    .Build();

Real-world example: feature-flag-based payment provider

public interface IFeatureFlagService
{
    Task<bool> IsEnabledAsync(string flag, CancellationToken cancellationToken);
}

var services = new ServiceCollection();

services.AddSingleton<IFeatureFlagService, RemoteFeatureFlagService>();

services
    .AddAsyncStrategy<IPaymentService>(async (context, candidates) =>
    {
        var flags = context.ServiceProvider.GetRequiredService<IFeatureFlagService>();

        if (await flags.IsEnabledAsync("payments-canary", context.CancellationToken))
        {
            return candidates.OfType<CanaryPaymentService>().Single();
        }

        return await flags.IsEnabledAsync("payments-v2", context.CancellationToken)
            ? candidates.OfType<NewPaymentService>().Single()
            : candidates.OfType<LegacyPaymentService>().Single();
    })
    .AddCandidate<LegacyPaymentService>()
    .AddCandidate<NewPaymentService>()
    .AddCandidate<CanaryPaymentService>()
    .WithImplementation<PaymentServiceProxy>()
    .Build();

var provider = services.BuildServiceProvider();

// Anywhere in the app:
var paymentService = provider.GetRequiredService<IPaymentService>();
await paymentService.ChargeAsync(49.99m);

API reference

StrategyResolver<TDefinition>

Member Description
static Create(IServiceProvider, StrategyResolverFunc<T>, params T[]) Creates a resolver backed by a synchronous resolver function.
static CreateAsync(IServiceProvider, StrategyResolverAsyncFunc<T>, params T[]) Creates a resolver backed by an asynchronous resolver function.
TDefinition Resolve() Resolves synchronously. ThrowsInvalidOperationException if configured with an async resolver.
Task<TDefinition> ResolveAsync(CancellationToken) Resolves asynchronously. Works regardless of how the resolver was configured.
bool IsAsync true if this instance was created via CreateAsync.

IStrategyBuilder<TDefinition>

Member Description
AddCandidate<TCandidate>() Registers a candidate type in the container. ThrowsInvalidOperationException on duplicates.
WithImplementation<TImplementation>() RegistersTImplementation as the concrete type for TDefinition itself.
IServiceCollection Build() Finalizes registration. ThrowsInvalidOperationException if no candidates were added.
bool TryBuild(out IServiceCollection?) Finalizes registration without throwing; returnsfalse if no candidates were added.

ServiceCollectionExtensions

Method Description
AddStrategy<TDefinition>(StrategyResolverFunc<TDefinition>, ServiceLifetime = Scoped) Starts building a strategy with a synchronous resolver function.
AddAsyncStrategy<TDefinition>(StrategyResolverAsyncFunc<TDefinition>, ServiceLifetime = Scoped) Starts building a strategy with an asynchronous resolver function.

StrategyResolverContext

Member Description
IServiceProvider ServiceProvider Lets your resolver function resolve other services (e.g. a feature flag client).
CancellationToken CancellationToken Propagated fromResolveAsync(cancellationToken). CancellationToken.None for synchronous Resolve().

Design notes

  • Not a Factory. StrategyResolver<T> doesn't create new instances — it selects among instances that are already registered in the DI container. The selection logic itself (your resolver function) is the actual Strategy.
  • Sync and async are intentionally kept separate. Mixing them behind a single blocking call is a common source of deadlocks. Resolve() fails fast with a clear message if you configured an async resolver by mistake, rather than silently blocking a thread.
  • Duplicate candidates are a build-time error, not a silent no-op. Registering the same candidate type twice almost always indicates a copy-paste mistake, so AddCandidate<T>() throws instead of ignoring the duplicate.
Product Compatible and additional computed target framework versions.
.NET 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.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  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
1.0.2 251 9/4/2026
1.0.1 215 7/27/2026