Relay 1.0.3

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

πŸ”— Relay - Adaptive Dependency Injection

Made in Ukraine Relay License

Relay your dependency injection to the next level! A powerful, fluent library that extends Microsoft.Extensions.DependencyInjection with adaptive patterns for conditional routing, multi-relays, adapter chains, and dynamic service resolution.

Terms of use

By using this project or its source code, for any purpose and in any shape or form, you grant your implicit agreement to all of the following statements:

  • You unequivocally condemn Russia and its military aggression against Ukraine
  • You recognize that Russia is an occupant that unlawfully invaded a sovereign state
  • You agree that Russia is a terrorist state
  • You fully support Ukraine's territorial integrity, including its claims over temporarily occupied territories
  • You reject false narratives perpetuated by Russian state propaganda

To learn more about the war and how you can help, click here. Glory to Ukraine! πŸ‡ΊπŸ‡¦

🎯 Why Relay?

Transform the adapter pattern from a simple design pattern into a powerful architectural tool:

  • πŸ”„ Conditional Routing: Route to different implementations based on environment, context, or runtime conditions
  • πŸ“‘ Multi-Relay Broadcasting: Execute operations across multiple implementations with various strategies
  • πŸ”— True Adapter Pattern: Seamlessly integrate legacy systems and incompatible interfaces
  • ⛓️ Adapter Chains: Build complex transformation pipelines (Aβ†’Bβ†’Cβ†’X)
  • 🏭 Relay Factories: Key-based service creation with flexible configuration
  • ⚑ Performance Optimized: Efficient resolution with comprehensive lifetime management

πŸš€ Quick Start

Installation

dotnet add package Relay

Basic Usage

using Relay;

// Configure services
services.AddRelayServices();

// Basic relay
services.AddRelay<IPaymentService, StripePaymentRelay>()
    .WithScopedLifetime();

// Conditional relay
services.AddConditionalRelay<IPaymentService>()
    .When(ctx => ctx.Environment == "Development").RelayTo<MockPaymentService>()
    .When(ctx => ctx.Environment == "Production").RelayTo<StripePaymentService>()
    .Build();

// Multi-relay broadcasting
services.AddMultiRelay<INotificationService>(config => config
    .AddRelay<EmailNotificationService>()
    .AddRelay<SmsNotificationService>()
    .WithStrategy(RelayStrategy.Broadcast)
).Build();

πŸ“‹ Complete Feature Set

1. Basic Relay Registration

services.AddRelay<IPaymentService, StripePaymentRelay>()
    .WithScopedLifetime()
    .DecorateWith<LoggingDecorator>();

2. Conditional Routing

services.AddConditionalRelay<IPaymentService>()
    .WithScopedLifetime()
    .When(ctx => ctx.Environment == "Development")
        .RelayTo<MockPaymentService>()
    .When(ctx => ctx.Properties["PaymentMethod"].Equals("Stripe"))
        .RelayTo<StripePaymentService>()
    .When(ctx => ctx.Properties["PaymentMethod"].Equals("PayPal"))
        .RelayTo<PayPalPaymentService>()
    .Otherwise<DefaultPaymentService>()
    .Build();

3. Multi-Relay Broadcasting

// Broadcast to all services
services.AddMultiRelay<INotificationService>(config => config
    .AddRelay<EmailNotificationService>(ServiceLifetime.Singleton)
    .AddRelay<SmsNotificationService>(ServiceLifetime.Scoped)
    .AddRelay<PushNotificationService>(ServiceLifetime.Transient)
    .WithStrategy(RelayStrategy.Broadcast)
).Build();

// Failover strategy
services.AddMultiRelay<IStorageService>(config => config
    .AddRelay<PrimaryStorageService>()
    .AddRelay<SecondaryStorageService>()
    .AddRelay<BackupStorageService>()
    .WithStrategy(RelayStrategy.Failover)
).Build();

4. True Adapter Pattern

// Your RefactoringGuru example becomes:
services.AddAdapter<ITarget, Adaptee>()
    .WithScopedLifetime()
    .Using<Adapter>();

// Legacy system integration
services.AddAdapter<IModernPaymentService, LegacyPaymentGateway>()
    .WithScopedLifetime()
    .WithAdapteeLifetime(ServiceLifetime.Singleton)
    .Using<LegacyPaymentAdapter>();

// Factory-based adapters
services.AddAdapter<INotificationService, ThirdPartyEmailService>()
    .Using(emailService => new EmailNotificationAdapter(emailService));

5. Adapter Chains (A→B→C→X)

// Complex transformation pipeline
services.AddAdapterChain<IResult>()
    .From<RawData>()                           // A (source)
    .Then<ValidatedData, ValidationAdapter>()  // A β†’ B
    .Then<EnrichedData, EnrichmentAdapter>()   // B β†’ C  
    .Finally<ProcessedResultAdapter>()         // C β†’ X (final)
    .Build();

// Strongly-typed chain
services.AddTypedAdapterChain<XmlData, DomainModel>()
    .Then<JsonData, XmlToJsonAdapter>()
    .Then<DataDto, JsonToDtoAdapter>()  
    .Then<DomainModel, DtoToDomainAdapter>()
    .Build();

6. Relay Factory

services.AddRelayFactory<IPaymentService>(factory => factory
    .RegisterRelay("stripe", provider => new StripeRelay())
    .RegisterRelay("paypal", provider => new PayPalRelay())
    .RegisterRelay("crypto", provider => new CryptoRelay())
    .SetDefaultRelay("stripe")
).Build();

// Usage
var factory = serviceProvider.GetService<IRelayFactory<IPaymentService>>();
var paymentService = factory.CreateRelay("stripe");

7. Auto-Discovery

services.AddRelay(config => config
    .FromAssemblyOf<IPaymentService>()
    .WithDefaultLifetime(ServiceLifetime.Scoped)
    .RegisterRelays()
);

// Advanced discovery
services.AddAdaptersFromAssembly<IPaymentService>(ServiceLifetime.Scoped);

8. Comprehensive Lifetime Management

// Different lifetimes for different components
services.AddMultiRelay<INotificationService>(config => config
    .WithDefaultLifetime(ServiceLifetime.Scoped)
    .AddRelay<EmailService>(ServiceLifetime.Singleton)    // Expensive to create
    .AddRelay<SmsService>(ServiceLifetime.Scoped)         // Request-specific
    .AddRelay<PushService>(ServiceLifetime.Transient)     // Independent operations
    .WithStrategy(RelayStrategy.Broadcast)
).Build();

🎯 Real-World Use Cases

1. Multi-Environment Deployments

  • Development: Mock services for fast development
  • Staging: Test services with real integrations
  • Production: Production services with monitoring

2. Legacy System Modernization

  • Gradual migration from old to new systems
  • Bridge incompatible interfaces
  • Maintain backward compatibility

3. Multi-Provider Integration

  • Payment processors (Stripe, PayPal, Square)
  • Cloud storage (AWS, Azure, Google Cloud)
  • Authentication providers (Auth0, Azure AD, Custom)

4. Data Processing Pipelines

  • Raw β†’ Validated β†’ Enriched β†’ Processed
  • Multi-step transformations with error handling
  • Complex business logic workflows

5. Multi-Channel Broadcasting

  • Notifications (Email, SMS, Push, Slack)
  • Logging (Console, File, Database, Cloud)
  • Caching (Memory, Redis, Database)

πŸ”§ Advanced Features

Conditional Chain Selection

services.AddConditionalAdapterChain<IUserService>()
    .When(ctx => ctx.Environment == "Development")
    .UseChain(chain => chain
        .From<MockDatabase>()
        .Finally<MockUserService>())
    .When(ctx => ctx.Environment == "Production") 
    .UseChain(chain => chain
        .From<LegacyDatabase>()
        .Then<IModernOrm, LegacyToOrmAdapter>()
        .Then<IRepository<User>, OrmToRepositoryAdapter<User>>()
        .Finally<RepositoryToServiceAdapter>())
    .Build();

Parallel Chain Execution

services.AddParallelAdapterChains<IDataProcessor>()
    .AddChain("fast", chain => chain
        .From<RawData>()
        .Then<CachedData, FastCacheAdapter>()
        .Finally<FastProcessorAdapter>())
    .AddChain("thorough", chain => chain
        .From<RawData>()
        .Then<ValidatedData, ValidationAdapter>()
        .Then<EnrichedData, EnrichmentAdapter>()
        .Finally<ThoroughProcessorAdapter>())
    .Build();

// Usage
var chainFactory = serviceProvider.GetService<IAdapterChainFactory<IDataProcessor>>();
var processor = chainFactory.CreateFromChain("thorough");

πŸ—οΈ Architecture Benefits

βœ… Clean Separation of Concerns

  • Each adapter/relay has a single responsibility
  • Clear interfaces between components
  • Easy to test and maintain

βœ… Flexible Configuration

  • Runtime decision making
  • Environment-specific implementations
  • Feature flag support

βœ… Performance Optimized

  • Efficient service resolution
  • Proper lifetime management
  • Minimal overhead

βœ… Enterprise Ready

  • Thread-safe operations
  • Comprehensive error handling
  • Extensive logging support

πŸ§ͺ Testing Support

// Easy mocking for tests
services.AddConditionalRelay<IPaymentService>()
    .When(ctx => ctx.Properties["TestMode"].Equals("Mock"))
        .RelayTo<MockPaymentService>()
    .When(ctx => ctx.Properties["TestMode"].Equals("Integration"))
        .RelayTo<TestPaymentService>()
    .Build();

πŸ”§ Installation & Setup

Package Installation

# Package Manager
Install-Package Relay

# .NET CLI
dotnet add package Relay

# PackageReference
<PackageReference Include="Relay" Version="1.0.0" />

Basic Setup

using Relay;

public void ConfigureServices(IServiceCollection services)
{
    // Add relay services
    services.AddRelayServices();
    
    // Configure your relays
    services.AddRelay(config => config
        .FromAssemblyOf<IPaymentService>()
        .RegisterRelays()
    );
}

πŸ“š Documentation

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

🌟 Support

If you find this project helpful, please consider:

  • ⭐ Starring the repository
  • πŸ› Reporting issues
  • πŸ’‘ Suggesting new features
  • πŸ“– Improving documentation

Relay transforms dependency injection from simple service registration into a powerful architectural pattern for building maintainable, scalable .NET applications! πŸš€

Product Compatible and additional computed target framework versions.
.NET 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 was computed.  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.3 66 6/7/2025