### Complete Dependency Injection Setup with C# Source: https://github.com/paulaolileal/myth/blob/main/Myth.Repository.EntityFramework/README.md A comprehensive example of setting up dependency injection in a .NET application using C#. It includes database context configuration, repository registration, and Unit of Work setup. ```csharp var builder = WebApplication.CreateBuilder( args ); // Database configuration builder.Services.AddDbContext( options => { options.UseSqlServer( builder.Configuration.GetConnectionString( "DefaultConnection" ) ); options.EnableSensitiveDataLogging( builder.Environment.IsDevelopment( ) ); options.EnableDetailedErrors( builder.Environment.IsDevelopment( ) ); } ); // Repository registration builder.Services.AddRepositories( ); // Auto-register all repositories // Unit of Work registration builder.Services.AddUnitOfWorkForContext( ); // Build app with cross-library dependency resolution var app = builder.BuildApp( ); app.Run( ); ``` -------------------------------- ### Myth.Tool CLI Project Setup Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Demonstrates how to use the Myth.Tool CLI to set up a new project. It shows commands for creating a new project with a clean structure and for setting up a project while keeping existing examples. ```bash # Setup new project with clean structure myth setup MyProject --clean # Setup project keeping examples myth setup MyProject ``` -------------------------------- ### Setup New Myth Project Source: https://github.com/paulaolileal/myth/blob/main/Myth.Tool/README.md Initializes a new Myth project with a clean structure. The `--clean` option removes example files and sets up a minimal project context. ```bash myth setup MyProject --clean ``` -------------------------------- ### Pagination Examples Source: https://github.com/paulaolileal/myth/blob/main/Myth.Repository.EntityFramework/README.md Examples demonstrating how to implement pagination using both expression-based and pagination object approaches. ```APIDOC ## Pagination Examples ### Description Examples demonstrating how to implement pagination using the repository's `SearchPaginatedAsync` method. ### Using Expression-Based Pagination This method allows specifying `take`, `skip`, and `orderPredicate` directly. ```csharp public async Task> GetProductsAsync( int page, int pageSize ) { var skip = ( page - 1 ) * pageSize; return await _productRepository.SearchPaginatedAsync( predicate: p => p.IsAvailable, take: pageSize, skip: skip, orderPredicate: p => p.Price ); } ``` ### Using Pagination Object This method accepts a `Pagination` object for more structured pagination control. ```csharp public async Task> GetProductsAsync( Pagination pagination ) { return await _productRepository.SearchPaginatedAsync( predicate: p => p.IsAvailable, pagination: pagination, orderPredicate: p => p.Name ); } ``` ### Result Structure The `IPaginated` interface defines the structure of the paginated results. ```csharp public interface IPaginated { IEnumerable Items { get; } int TotalItems { get; } int PageSize { get; } int CurrentPage { get; } int TotalPages { get; } bool HasPrevious { get; } bool HasNext { get; } } ``` ``` -------------------------------- ### Myth Setup for ASP.NET Core Applications Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Provides a step-by-step guide for setting up Myth libraries within an ASP.NET Core application. It covers adding core libraries, registering repositories, building the application with the global service provider, and adding necessary middleware. ```csharp using Myth.Extensions; var builder = WebApplication.CreateBuilder(args); // 1. Add core libraries builder.Services.AddFlow(config => config .UseTelemetry() .UseRetry(maxAttempts: 3, backoffMs: 1000) .UseActions(actions => actions .UseInMemory() // or .UseKafka() / .UseRabbitMQ() .UseCaching() .ScanAssemblies(typeof(Program).Assembly) .EnableAutoSubscription())); builder.Services.AddGuard(); builder.Services.AddMorph(); // 2. Register repositories and services builder.Services.AddDbContext(); builder.Services.AddScoped(); builder.Services.AddScoped(); // 3. Build with global service provider (CRITICAL!) var app = builder.BuildApp(); // NOT builder.Build() // 4. Add middleware app.UseGuard(); // Validation exception handling app.MapControllers(); app.Run(); ``` -------------------------------- ### Prompting Examples for AI Assistants using Myth Skill Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Provides example prompts for interacting with AI assistants to leverage the Myth skill for various development tasks. These examples cover project setup, adding validation, creating command handlers, setting up specifications, and object transformation. ```text "Use the myth skill to setup a new ASP.NET Core application with CQRS, validation, and pipelines" "Use the myth skill with library=Guard to add validation rules for a CreateUserDto with email, age, and password fields" "Use the myth skill with library=Flow.Actions and operation=command to create a CreateOrderCommand handler with validation, repository, and event publishing" "Use the myth skill with library=Specification to create reusable query specifications for Product entity with filters for category, price range, and active status" "Use the myth skill with library=Morph to create bidirectional mapping between Order entity and OrderDto" "Use the myth skill to configure a complete CQRS setup with Flow.Actions, Guard validation, Repository pattern, and Specifications for an e-commerce order system" ``` -------------------------------- ### Pipeline Starting Methods (C#) Source: https://github.com/paulaolileal/myth/blob/main/Myth.Flow.Actions/README.md Provides static methods to initiate a pipeline. 'Start' begins a pipeline with a specific request type, while 'Start()' initiates a pipeline without an initial request. ```csharp Pipeline.Start( TRequest request ) Pipeline.Start( ) ``` -------------------------------- ### Myth.Flow Actions Setup and CQRS Usage (C#) Source: https://github.com/paulaolileal/myth/blob/main/CLAUDE.md Illustrates the setup of Myth.Flow actions in Program.cs, including in-memory storage, caching, and assembly scanning. It provides examples of using the dispatcher for CQRS commands, queries with caching, and event publishing. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddFlow(config => config .UseTelemetry() .UseRetry(3, 1000) .UseActions(actions => actions .UseInMemory() .UseCaching() .ScanAssemblies(typeof(Program).Assembly))); var app = builder.BuildApp(); // Enables cross-library dependencies // Using CQRS: // Dispatch command var commandResult = await dispatcher.DispatchCommandAsync(new CreateOrderCommand { ... }); // Query with caching var queryResult = await dispatcher.DispatchQueryAsync( new GetOrderQuery { OrderId = 123 }, new CacheOptions { Enabled = true, Ttl = TimeSpan.FromMinutes(5) } ); // Publish event await dispatcher.PublishEventAsync(new OrderCreatedEvent { ... }); ``` -------------------------------- ### Install Optional RabbitMQ Support Source: https://github.com/paulaolileal/myth/blob/main/Myth.Flow.Actions/README.md Installs the RabbitMQ.Client package for RabbitMQ support within the Myth framework. This is an optional dependency. ```bash # For RabbitMQ support dotnet add package RabbitMQ.Client ``` -------------------------------- ### Myth.Testing HTTP Client Mocking Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Shows how to mock an HttpClient using Myth.Testing.Mocks. This example demonstrates setting up a GET request with a JSON response and a specific status code. ```csharp using Myth.Testing.Mocks; var httpClientMock = new HttpClientMock() .SetupGet("/users/1") .ReturnsJson(new UserDto { Id = 1, Name = "John" }) .WithStatusCode(HttpStatusCode.OK); var httpClient = httpClientMock.CreateClient(); ``` -------------------------------- ### EF Core Implementation: DbContext and Repositories (C#) Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Provides the Entity Framework Core implementation for repository interfaces, including DbContext setup and dependency injection registration. This example shows configuring an AppDbContext and registering repositories and the Unit of Work. ```csharp using Myth.Contexts; using Myth.Repository.EntityFramework.Repositories; // Define DbContext public class AppDbContext : BaseContext { public DbSet Products { get; set; } public DbSet Orders { get; set; } public AppDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Configure entities } } // Implement Repository public class ProductRepository : ReadWriteRepositoryAsync, IProductRepository { public ProductRepository(AppDbContext context) : base(context) { } } // Register services.AddDbContext(options => options.UseSqlServer(connectionString)); services.AddScoped(); services.AddScoped>(); ``` -------------------------------- ### ASP.NET Core Example: API Endpoint and Configuration (C#) Source: https://github.com/paulaolileal/myth/blob/main/Myth.Commons/README.md Demonstrates setting up an ASP.NET Core application with global JSON configuration for snake_case and ignoring null values. It includes an example API endpoint for fetching paginated orders using scoped services and repositories. ```csharp // Program.cs - ASP.NET Core var builder = WebApplication.CreateBuilder(args); // Configure global JSON JsonExtensions.Configure(settings => { settings.CaseStrategy = CaseStrategy.SnakeCase; settings.IgnoreNullValues = true; }); // Build app (initializes MythServiceProvider automatically) var app = builder.BuildApp(); app.MapGet("/orders", async ( [FromQuery] Pagination pagination, IScopedService repository) => { return await repository.ExecuteAsync(async repo => { var orders = await repo.GetPaginatedAsync(pagination); return Results.Ok(orders); }); }); app.Run(); ``` -------------------------------- ### C# Read-Write Repository Implementation Example Source: https://github.com/paulaolileal/myth/blob/main/Myth.Repository.EntityFramework/README.md Demonstrates how to implement the IReadWriteRepositoryAsync interface by inheriting from ReadWriteRepositoryAsync. This example shows a concrete repository for a 'Product' entity. ```csharp public class ProductRepository : ReadWriteRepositoryAsync, IProductRepository { public ProductRepository( ApplicationDbContext context ) : base( context ) { } } ``` -------------------------------- ### Myth Setup for Console Applications Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Details the setup process for integrating Myth libraries into a console application. It includes configuring services, registering custom services, and building the application with the global service provider for dependency resolution. ```csharp var services = new ServiceCollection(); services.AddFlow(config => config.UseTelemetry().UseRetry(3, 100)); services.AddGuard(); services.AddMorph(); // Register your services services.AddScoped(); // Build with global provider var serviceProvider = services.BuildWithGlobalProvider(); // Use services var dataService = serviceProvider.GetRequiredService(); await dataService.ProcessDataAsync(); ``` -------------------------------- ### Install Optional Kafka Support Source: https://github.com/paulaolileal/myth/blob/main/Myth.Flow.Actions/README.md Installs the Confluent.Kafka package for Kafka support within the Myth framework. This is an optional dependency. ```bash # For Kafka support dotnet add package Confluent.Kafka ``` -------------------------------- ### Complete C# Test Suite Example for MyApp Source: https://github.com/paulaolileal/myth/blob/main/Myth.Testing/README.md Provides a structural example of a comprehensive test suite for a C# application named MyApp. It includes placeholders for different types of tests: unit, integration (database and HTTP), performance, and end-to-end tests. ```csharp namespace MyApp.Tests { // Unit tests public class UserServiceUnitTests : BaseTests { /* ... */ } // Integration tests with database public class UserRepositoryIntegrationTests : BaseDatabaseTests { /* ... */ } // Integration tests with HTTP public class UserApiIntegrationTests : BaseTests { /* ... */ } // Performance tests public class UserPerformanceTests : BaseTests { /* ... */ } // End-to-end tests [Collection("E2E Tests")] public class UserE2ETests : IClassFixture> { /* ... */ } } ``` -------------------------------- ### Install Myth.Commons Package Source: https://github.com/paulaolileal/myth/blob/main/Myth.Commons/README.md Installs the Myth.Commons NuGet package using the .NET CLI. This package provides various utility features for .NET applications. ```bash dotnet add package Myth.Commons ``` -------------------------------- ### Install Myth.Testing Package (Bash) Source: https://github.com/paulaolileal/myth/blob/main/Myth.Testing/README.md Installs the Myth.Testing NuGet package using the .NET CLI. This command adds the package reference to your project file. ```bash dotnet add package Myth.Testing ``` -------------------------------- ### Setup Myth.Guard in Program.cs Source: https://github.com/paulaolileal/myth/blob/main/CLAUDE.md Registers Myth.Guard services and adds its middleware for exception handling in the application pipeline. This is the initial setup required for using Myth.Guard. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddGuard(); var app = builder.BuildApp(); // Enables cross-library dependencies app.UseGuard(); // Add middleware for exception handling ``` -------------------------------- ### Start Pipeline with Default Configuration (C#) Source: https://github.com/paulaolileal/myth/blob/main/Myth.Flow/README.md Illustrates starting a pipeline with its default configuration. This is the simplest way to initiate a pipeline, suitable for straightforward processing tasks where custom configurations are not immediately needed. ```csharp var result = await Pipeline.Start(context) .StepAsync(ctx => ProcessAsync(ctx)) .ExecuteAsync(); ``` -------------------------------- ### Install Myth.Tool CLI Source: https://github.com/paulaolileal/myth/blob/main/Myth.Tool/README.md Installs the Myth.Tool as a global .NET tool. This command is used to add the CLI to your system, allowing you to use its code generation capabilities. ```bash dotnet tool install -g Myth.Tool ``` -------------------------------- ### TypeProvider API Examples Source: https://github.com/paulaolileal/myth/blob/main/Myth.DependencyInjection/README.md Demonstrates the usage of the static TypeProvider class for discovering application types, assemblies, and namespaces. ```csharp // Get base namespace var ns = TypeProvider.BaseApplicationNamespace; // "MyCompany" from "MyCompany.ECommerce.Domain" // Get all assemblies var assemblies = TypeProvider.ApplicationAssemblies; // Get all types var allTypes = TypeProvider.ApplicationTypes; // Get types implementing interface var repositories = TypeProvider.GetTypesAssignableFrom(); var handlers = TypeProvider.GetTypesAssignableFrom(); var validators = TypeProvider.GetTypesAssignableFrom(); ``` -------------------------------- ### Register Services in Startup (C#) Source: https://github.com/paulaolileal/myth/blob/main/Myth.Repository.EntityFramework/README.md Shows how to configure the application's startup services. This includes registering the DbContext with SQL Server support and automatically registering all repositories using AddRepositories(). ```csharp var builder = WebApplication.CreateBuilder( args ); // Register DbContext builder.Services.AddDbContext( options => options.UseSqlServer( builder.Configuration.GetConnectionString( "DefaultConnection" ) ) ); // Automatically register ALL repositories builder.Services.AddRepositories( ); var app = builder.BuildApp( ); // Use BuildApp() for cross-library dependency resolution app.Run( ); ``` -------------------------------- ### HTTP GET Operations in C# Source: https://github.com/paulaolileal/myth/blob/main/Myth.Rest/README.md This code provides examples of performing HTTP GET requests using the REST client. It demonstrates how to specify the endpoint and include query parameters for filtering or retrieving specific resources. These are fundamental operations for fetching data from APIs. ```csharp .DoGet("users") .DoGet("users/123") .DoGet("products?category=electronics&sort=price") ``` -------------------------------- ### Basic Repository Implementation and Usage (C#) Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Demonstrates the basic implementation of a product repository using interfaces and classes, including dependency injection registration and service layer usage. It defines an interface for product repository operations and its concrete implementation. ```csharp // Interface public interface IProductRepository : IReadWriteRepositoryAsync { } // Implementation public class ProductRepository : ReadWriteRepositoryAsync, IProductRepository { public ProductRepository(AppDbContext context) : base(context) { } } // Registration services.AddScoped(); // Usage public class ProductService { private readonly IProductRepository _repository; public async Task CreateAsync(CreateProductDto dto) { var product = new Product { Name = dto.Name, Price = dto.Price }; await _repository.AddAsync(product); return product; } public async Task> GetAllAsync() { return await _repository.GetAllAsync(); } } ``` -------------------------------- ### Console Application Setup with Myth.Flow Source: https://github.com/paulaolileal/myth/blob/main/Myth.Flow/README.md Sets up Myth.Flow services for a console application or background service using `services.BuildWithGlobalProvider()`. This example configures telemetry and retry policies, and registers services like `ValidationService` and `ProcessingService`. ```csharp var services = new ServiceCollection(); services.AddFlow(config => config .UseTelemetry() .UseRetry(3, 100)); services.AddScoped(); services.AddScoped(); var serviceProvider = services.BuildWithGlobalProvider(); ``` -------------------------------- ### Myth.Testing Base Test Class Setup Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Illustrates setting up a base test class using Myth.Testing.Repositories and Myth.Testing.Extensions. It shows how to configure services, including repositories and guards, and create an instance of the service under test. ```csharp using Myth.Testing.Repositories; using Myth.Testing.Extensions; public class ProductServiceTests : BaseDatabaseTests { private readonly ProductService _service; public ProductServiceTests() : base() { AddServices(services => { services.AddScoped(); services.AddScoped(); services.AddGuard(); services.AddMorph(); }); _service = CreateInstance(); } [Fact] public async Task CreateProduct_ShouldSucceed_WhenValid() { // Arrange var dto = new CreateProductDto { Name = "Test", Price = 10.00m }; // Act var result = await _service.CreateProductAsync(dto); // Assert result.Should().NotBeNull(); result.Name.Should().Be("Test"); } ``` -------------------------------- ### Define and Handle Get Order Query with Caching in C# Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Defines a query to retrieve an order by its ID and its corresponding handler. The handler fetches the order from the repository and returns it as an OrderDto. The usage example demonstrates dispatching the query with caching enabled. ```csharp public record GetOrderQuery(Guid OrderId) : IQuery; public class GetOrderHandler : IQueryHandler { private readonly IScopedService _repository; public async Task> HandleAsync( GetOrderQuery query, CancellationToken ct) { var spec = SpecBuilder.Create() .And(o => o.Id == query.OrderId); var order = await _repository.ExecuteAsync(repo => repo.FirstOrDefaultAsync(spec, ct)); if (order == null) { return QueryResult.Failure("Order not found"); } var dto = order.To(); return QueryResult.Success(dto); } } // Usage with cache [HttpGet("{id}")] public async Task Get(Guid id) { var query = new GetOrderQuery(id); var cacheOptions = new CacheOptions { Enabled = true, Ttl = TimeSpan.FromMinutes(5), CacheKey = $"order:{id}" }; var result = await _dispatcher.DispatchQueryAsync( query, cacheOptions); return result.IsSuccess ? Ok(result.Data) : NotFound(); } ``` -------------------------------- ### Configure Services with Options and Conditional Logic (C#) Source: https://github.com/paulaolileal/myth/blob/main/Myth.Testing/README.md Demonstrates bulk service configuration including framework services, application services, options configuration, and conditional service registration based on environment variables. This is useful for setting up complex application environments. ```csharp public class ComplexServiceTests : BaseTests { public ComplexServiceTests() { // Bulk service configuration ConfigureServices(services => { // Add framework services services.AddLogging(); services.AddMemoryCache(); services.AddHttpClient(); // Add application services services.AddTransient(); services.AddScoped(); services.AddSingleton(); // Configure options services.Configure(settings => { settings.ApiUrl = "https://test-api.com"; settings.Timeout = TimeSpan.FromSeconds(30); }); // Add conditional services if (Environment.GetEnvironmentVariable("TEST_MODE") == "INTEGRATION") { services.AddTransient(); } else { services.AddTransient(); } }); } } ``` -------------------------------- ### Configuration - InMemory Broker Setup (C#) Source: https://github.com/paulaolileal/myth/blob/main/Myth.Flow.Actions/README.md Shows how to configure the application services to use an in-memory message broker. This includes setting up dead-letter queue options and maximum retry attempts for message processing. It also includes scanning assemblies for relevant types. ```csharp services.AddFlow( config => config .UseActions( actions => actions .UseInMemory( options => { options.UseDeadLetterQueue = true; options.MaxRetries = 3; }) .ScanAssemblies( typeof( Program ).Assembly ))); ``` -------------------------------- ### Manual Service Registration Example (C#) Source: https://github.com/paulaolileal/myth/blob/main/Myth.DependencyInjection/README.md Demonstrates the traditional, manual way of registering services in ASP.NET Core's Startup.cs. This approach requires explicit registration for each service, leading to verbose code and potential for errors if registrations are missed. ```csharp services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); // ... 200 more lines ... // New developer adds IPaymentRepository but forgets to register it → runtime crash ``` -------------------------------- ### ASP.NET Core Application Setup with Myth Extensions Source: https://github.com/paulaolileal/myth/blob/main/README.md Demonstrates how to configure an ASP.NET Core application using various Myth ecosystem extensions. This includes setting up validation, pipeline orchestration (CQRS), object transformation, API versioning, and service registration. It highlights the use of a global service provider for cross-library integration. ```csharp using Myth.Extensions; var builder = WebApplication.CreateBuilder(args); // Add comprehensive validation builder.Services.AddGuard(); // Add pipeline orchestration with CQRS builder.Services.AddFlow(config => config .UseTelemetry() .UseRetry(maxAttempts: 3, backoffMs: 1000) .UseActions(actions => actions .UseInMemory() // or .UseKafka() / .UseRabbitMQ() .UseCaching() .ScanAssemblies(typeof(Program).Assembly))); // Add object transformation builder.Services.AddMorph(); // Add API versioning and Swagger builder.Services.AddVersioning(1.0); builder.Services.AddSwaggerVersioned(settings => { settings.Title = "My Enterprise API"; settings.Description = "Production-ready API with comprehensive features"; }); // Auto-register repositories and services builder.Services.AddServiceFromType(); builder.Services.AddServiceFromType(); // Build with global service provider (enables cross-library integration) var app = builder.BuildApp(); // Add validation middleware app.UseGuard(); app.UseSwaggerVersioned(); app.MapControllers(); app.Run(); ``` -------------------------------- ### C# Repository Testing with Database Initialization and Cleanup Source: https://github.com/paulaolileal/myth/blob/main/Myth.Testing/README.md This C# code snippet demonstrates a robust pattern for testing repository methods that interact with a database. It includes essential steps like initializing the database before tests, seeding data, performing actions, asserting results, and crucially, cleaning up the database after each test to ensure isolation. It utilizes xUnit for testing and FluentAssertions for assertions. ```csharp namespace MyApp.Tests.Repositories { public class UserRepositoryTests : BaseDatabaseTests { private readonly UserRepository _repository; public UserRepositoryTests() { AddService(); _repository = GetRequiredService(); } [Fact] public async Task CreateUser_ShouldPersistCorrectly() { // Always initialize database first await InitializeDatabaseAsync(); try { // Arrange var user = new UserEntityBuilder(_faker) .WithName("Test User") .WithEmail("test@example.com") .Build(); // Act var result = await _repository.CreateAsync(user); // Assert result.Should().NotBeNull(); result.Id.Should().NotBeEmpty(); // Verify in database var context = GetContext(); var savedUser = await context.Users.FindAsync(result.Id); savedUser.Should().NotBeNull(); savedUser.Name.Should().Be("Test User"); savedUser.Email.Should().Be("test@example.com"); savedUser.CreatedAt.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(5)); } finally { // Always cleanup to ensure test isolation await CleanupDatabaseAsync(); } } [Fact] public async Task GetUsersByStatus_ShouldReturnCorrectUsers() { await InitializeDatabaseAsync(); try { // Arrange - Seed test data var activeUsers = new UserEntityBuilder(_faker) .WithIsActive(true) .BuildList(3); var inactiveUsers = new UserEntityBuilder(_faker) .WithIsActive(false) .BuildList(2); var context = GetContext(); await context.Users.AddRangeAsync(activeUsers.Concat(inactiveUsers)); await context.SaveChangesAsync(); // Act var retrievedActiveUsers = await _repository.GetByStatusAsync(isActive: true); // Assert retrievedActiveUsers.Should().HaveCount(3); retrievedActiveUsers.Should().OnlyContain(u => u.IsActive); retrievedActiveUsers.Should().BeEquivalentTo(activeUsers, options => options.Excluding(u => u.Id)); } finally { await CleanupDatabaseAsync(); } } [Fact] public async Task ConcurrentUpdates_ShouldHandleOptimisticConcurrency() { await InitializeDatabaseAsync(); try { // Arrange var user = new UserEntityBuilder(_faker).Build(); var context = GetContext(); await context.Users.AddAsync(user); await context.SaveChangesAsync(); // Act - Simulate concurrent updates var user1 = await _repository.GetByIdAsync(user.Id); var user2 = await _repository.GetByIdAsync(user.Id); user1.Name = "Updated by User 1"; user2.Name = "Updated by User 2"; await _repository.UpdateAsync(user1); // Assert - Second update should fail due to concurrency await _repository.Invoking(r => r.UpdateAsync(user2)) .Should().ThrowAsync(); } finally { await CleanupDatabaseAsync(); } } } } ``` -------------------------------- ### Install Myth.Flow.Actions Package Source: https://github.com/paulaolileal/myth/blob/main/Myth.Flow.Actions/README.md Installs the core Myth.Flow.Actions package using the .NET CLI. This package is essential for using the Myth framework. ```bash dotnet add package Myth.Flow.Actions ``` -------------------------------- ### Test Myth.Flow Pipelines in C# Source: https://github.com/paulaolileal/myth/blob/main/Myth.Testing/README.md Shows how to set up and test a pipeline using Myth.Flow in C#. This example configures services for the flow, a user processing pipeline, and mock implementations for user validation and repository, then executes the pipeline. ```csharp public class PipelineTests : BaseTests { private readonly UserProcessingPipeline _pipeline; public PipelineTests() { ConfigureServices(services => { services.AddFlow(); services.AddTransient(); services.AddTransient(); services.AddTransient(); }); _pipeline = GetRequiredService(); } [Fact] public async Task Pipeline_ShouldProcessUserSuccessfully() { // Arrange var context = new UserProcessingContext { User = new UserBuilder(_faker).Build() }; // Act var result = await _pipeline.ExecuteAsync(context); // Assert result.IsSuccess.Should().BeTrue(); result.Value.User.Should().NotBeNull(); result.Value.IsProcessed.Should().BeTrue(); } } ``` -------------------------------- ### Simple Validation Error Example (JSON) Source: https://github.com/paulaolileal/myth/blob/main/docs/errors/validation.md An example of a simple validation error response, indicating a single missing required field. ```json { "type": "https://github.com/paulaolileal/myth/blob/main/docs/errors/validation.md", "title": "One or more validation errors occurred", "status": 400, "instance": "/api/users", "traceId": "00-fb27f88950d75be0ee3c0787c3bcb772-f52eb8f38d98b38f-00", "errors": { "name": [ "Name is required" ] } } ``` -------------------------------- ### JSON Serialization and Deserialization Examples Source: https://github.com/paulaolileal/myth/blob/main/Myth.Commons/README.md Demonstrates various use cases for the JSON extension methods, including basic serialization, serialization with custom settings, deserialization, safe deserialization, JSON validation, and using global configuration for consistent JSON handling. ```csharp // Basic serialization var user = new User { Name = "John", Email = "john@example.com" }; var json = user.ToJson(); // With settings var minified = user.ToJson(s => s.Minify().IgnoreNull()); // Deserialization var user = json.FromJson(); // Safe deserialization var user = json.SafeFromJson(); // Returns null if invalid // Validation if (content.IsValidJson()) { var data = content.FromJson(); } // With HTTP context try { var user = json.FromJsonOrThrow(HttpStatusCode.BadRequest); } catch (InvalidJsonResponseException ex) { Console.WriteLine($"Status: {ex.StatusCode}, Content: {ex.RawContent}"); } // Global configuration JsonExtensions.Configure(settings => { settings.CaseStrategy = CaseStrategy.SnakeCase; settings.IgnoreNullValues = true; settings.UseInterfaceConverter(); }); // Now all ToJson/FromJson calls use these settings var json = user.ToJson(); // Uses snake_case and ignores nulls ``` -------------------------------- ### Complete CQRS Example: User Creation Source: https://github.com/paulaolileal/myth/blob/main/README.md Demonstrates a complete Command Query Responsibility Segregation (CQRS) pattern for user creation. It includes a domain entity with validation, a command handler with a pipeline for validation, transformation, repository interaction, and event dispatching, and a controller to handle the incoming command. ```csharp public class CreateUserCommand : IValidatable, ICommand { public string Name { get; set; } public string Email { get; set; } public int Age { get; set; } public void Validate(ValidationBuilder builder, ValidationContextKey? context = null) { builder.For(Name, x => x.NotEmpty().MinimumLength(2).MaximumLength(100)); builder.For(Email, x => x.NotEmpty().Email()); builder.For(Age, x => x.GreaterThan(0).LessThan(150)); builder.InContext(ValidationContextKey.Create, b => { b.For(Email, x => x .RespectAsync(async (email, ct, sp) => { var userRepo = sp.GetRequiredService(); return !await userRepo.ExistsByEmailAsync(email, ct); }) .WithMessage("Email already exists")); }); } } public class CreateUserCommandHandler : ICommandHandler { private readonly IUserRepository _repository; private readonly IValidator _validator; private readonly IDispatcher _dispatcher; public CreateUserCommandHandler(IUserRepository repository, IValidator validator, IDispatcher dispatcher) { _repository = repository; _validator = validator; _dispatcher = dispatcher; } public async Task> HandleAsync(CreateUserCommand command, CancellationToken cancellationToken) { return await Pipeline.Start(command) .WithTelemetry("CreateUser") .WithRetry(maxAttempts: 3) .StepResultAsync(cmd => _validator.ValidateAndReturnAsync(cmd, ValidationContextKey.Create)) .Transform(cmd => cmd.To()) .StepAsync(entity => _repository.AddAsync(entity)) .TapAsync(entity => _dispatcher.PublishEventAsync(new UserCreatedEvent { UserId = entity.Id })) .Transform(entity => entity.To()) .ExecuteAsync(cancellationToken); } } [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] public class UsersController : ControllerBase { private readonly IDispatcher _dispatcher; public UsersController(IDispatcher dispatcher) { _dispatcher = dispatcher; } /// /// Creates a new user /// [HttpPost] public async Task CreateUser(CreateUserCommand command) { var result = await _dispatcher.DispatchCommandAsync(command); if (result.IsSuccess) return CreatedAtAction(nameof(GetUser), new { id = result.Data.Id }, result.Data); return BadRequest(result.ErrorMessage); } } ``` -------------------------------- ### Install Optional Redis Caching Support Source: https://github.com/paulaolileal/myth/blob/main/Myth.Flow.Actions/README.md Installs the Microsoft.Extensions.Caching.StackExchangeRedis package for Redis distributed caching support within the Myth framework. This is an optional dependency. ```bash # For Redis distributed caching dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis ``` -------------------------------- ### Console Application Setup with Myth Source: https://github.com/paulaolileal/myth/blob/main/CLAUDE.md Illustrates setting up a console application or background service with Myth's dependency injection, enabling cross-library resolution using `BuildWithGlobalProvider()`. ```csharp var services = new ServiceCollection(); services.AddFlow(); services.AddGuard(); var serviceProvider = services.BuildWithGlobalProvider(); // Now all libraries can resolve dependencies from each other var pipeline = Pipeline.Start(context); // Works! ``` -------------------------------- ### URL Encoding Example Source: https://github.com/paulaolileal/myth/blob/main/Myth.Commons/README.md Shows how the EncodeAsUrl extension method can be used to URL-encode a string. It also indicates that other data types are handled, although the example focuses on string encoding. ```csharp "hello world".EncodeAsUrl(); // "hello+world" true.EncodeAsUrl(); // Boolean 123.EncodeAsUrl(); // 123 ``` -------------------------------- ### Install Myth.Guard Package Source: https://github.com/paulaolileal/myth/blob/main/Myth.Guard/README.md This command installs the Myth.Guard NuGet package into your .NET project. This package provides the core validation functionalities. ```bash dotnet add package Myth.Guard ``` -------------------------------- ### Install Myth.Testing Package (PowerShell) Source: https://github.com/paulaolileal/myth/blob/main/Myth.Testing/README.md Installs the Myth.Testing NuGet package using the Package Manager Console in Visual Studio. This command adds the package reference to your project. ```powershell Install-Package Myth.Testing ``` -------------------------------- ### Unit Testing with Mocking in C# Source: https://github.com/paulaolileal/myth/blob/main/Myth.Repository/README.md Demonstrates unit testing for a ProductService in C# using Moq for mocking repository dependencies. The example shows how to set up mock behavior and assert method outcomes for retrieving a product by its ID. ```csharp public class ProductServiceTests { private readonly Mock _mockRepository; private readonly ProductService _service; public ProductServiceTests( ) { _mockRepository = new Mock( ); _service = new ProductService( _mockRepository.Object ); } [Fact] public async Task GetByIdAsync_ShouldReturnProduct_WhenExists( ) { var productId = Guid.NewGuid( ); var product = new Product { Id = productId, Name = "Test" }; _mockRepository .Setup( r => r.FirstOrDefaultAsync( It.IsAny>>( ), default ) ) .ReturnsAsync( product ); var result = await _service.GetByIdAsync( productId, default ); result.Should( ).NotBeNull( ); result.Id.Should( ).Be( productId ); } } ``` -------------------------------- ### C# ASP.NET Core Application Startup with Myth.Flow Source: https://github.com/paulaolileal/myth/blob/main/Myth.Flow/README.md Shows the basic setup for an ASP.NET Core application using Myth.Flow. It demonstrates how to register the flow services and build the application with the global service provider. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; public class Startup { public void ConfigureServices(IServiceCollection services) { // Register Myth.Flow services services.AddFlow(); // Register application-specific services services.AddScoped(); services.AddScoped(); // ... other services } public void Configure(IApplicationBuilder app) { // Build the application with the global service provider var builtApp = app.ApplicationBuilder.BuildApp(); // Assuming BuildApp() is an extension method // Configure middleware pipeline // ... builtApp.Run(); // Assuming builtApp has a Run() method } } ``` -------------------------------- ### Install Myth.Repository.EntityFramework via NuGet Source: https://github.com/paulaolileal/myth/blob/main/Myth.Repository.EntityFramework/README.md Installs the Myth.Repository.EntityFramework package using the .NET CLI or Package Manager Console. This package provides repository implementations for Entity Framework Core. ```bash dotnet add package Myth.Repository.EntityFramework ``` ```powershell Install-Package Myth.Repository.EntityFramework ``` -------------------------------- ### Usage Examples of Extension Methods in C# Source: https://github.com/paulaolileal/myth/blob/main/Myth.Specification/README.md Provides practical examples of how to use the IQueryable and IEnumerable extension methods for applying filters, sorting, pagination, and complete specifications. ```csharp var products = dbContext.Products; // Apply only filter var filtered = products.Filter(spec); // Apply only sorting var sorted = products.Sort(spec); // Apply only pagination var paginated = products.Paginate(spec); // Apply complete specification var result = products.Specify(spec); // In-memory filtering var memoryList = new List { /* ... */ }; var filtered = memoryList.Where(spec); // Uses compiled predicate ``` -------------------------------- ### ASP.NET Core Application Building Best Practice Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Demonstrates the correct way to build an ASP.NET Core application using `BuildApp()` and console applications using `BuildWithGlobalProvider()`. Avoids the incorrect use of `Build()` and `BuildServiceProvider()`. ```csharp // ✅ CORRECT - ASP.NET Core var app = builder.BuildApp(); // ❌ INCORRECT var app = builder.Build(); // ✅ CORRECT - Console App var serviceProvider = services.BuildWithGlobalProvider(); // ❌ INCORRECT var serviceProvider = services.BuildServiceProvider(); ``` -------------------------------- ### Pagination and Ordering with Query Specifications (C#) Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Demonstrates how to apply pagination (Skip, Take, WithPagination) and ordering (Order, OrderDescending) to query specifications. ```csharp var spec = SpecBuilder.Create() .IsActive() .Order(p => p.Name) // Ascending .OrderDescending(p => p.Price) // Descending .Skip(20) // Offset .Take(10) // Limit .WithPagination(new Pagination { PageNumber = 2, PageSize = 10 }); ``` -------------------------------- ### Create Application DbContext with BaseContext Source: https://github.com/paulaolileal/myth/blob/main/Myth.Repository.EntityFramework/README.md Defines a custom DbContext inheriting from Myth.Contexts.BaseContext. This setup allows for automatic discovery and application of entity configurations within the specified assembly, simplifying DbContext setup. ```csharp using Myth.Contexts; using Microsoft.EntityFrameworkCore; public class ApplicationDbContext : BaseContext { public ApplicationDbContext( DbContextOptions options ) : base( options ) { } public DbSet Users { get; set; } public DbSet Products { get; set; } } ``` -------------------------------- ### Implement Querying with Expressions in C# ProductService Source: https://github.com/paulaolileal/myth/blob/main/Myth.Repository/README.md Illustrates how to perform various querying operations on products using lambda expressions with the IProductRepository. This includes fetching by ID, filtering by category, counting active products, and checking for the existence or universality of certain conditions. ```csharp public class ProductService { private readonly IProductRepository _repository; public async Task GetByIdAsync( Guid id, CancellationToken ct ) { return await _repository.FirstOrDefaultAsync( p => p.Id == id, ct ); } public async Task> GetByCategoryAsync( string category, CancellationToken ct ) { return await _repository.SearchAsync( p => p.Category == category, ct ); } public async Task CountActiveProductsAsync( CancellationToken ct ) { return await _repository.CountAsync( p => p.IsActive, ct ); } public async Task HasExpensiveProductsAsync( CancellationToken ct ) { return await _repository.AnyAsync( p => p.Price > 1000, ct ); } public async Task AreAllActiveAsync( CancellationToken ct ) { return await _repository.AllAsync( p => p.IsActive, ct ); } } ``` -------------------------------- ### Conflict Status Validation Error Example (JSON) Source: https://github.com/paulaolileal/myth/blob/main/docs/errors/validation.md An example of a validation error response with a 409 Conflict status code, typically used for resource conflicts like duplicate entries. ```json { "type": "https://github.com/paulaolileal/myth/blob/main/docs/errors/validation.md", "title": "One or more validation errors occurred", "status": 409, "instance": "/api/users", "traceId": "00-abc123...", "errors": { "email": [ "Email already exists" ] } } ``` -------------------------------- ### Mock Service Replacement and Factory Registration (C#) Source: https://github.com/paulaolileal/myth/blob/main/Myth.Testing/README.md Illustrates how to replace existing services with mock implementations and register factory-based services. This is crucial for unit testing by isolating dependencies and controlling their behavior. ```csharp public class MockingTests : BaseTests { private readonly Mock _mockRepository; public MockingTests() { // Create mocks _mockRepository = new Mock(); // Setup mock behavior _mockRepository .Setup(r => r.GetByIdAsync(It.IsAny())) .ReturnsAsync(new User { Id = Guid.NewGuid(), Name = "Test User" }); // Register mock AddService(_mockRepository.Object); // Replace existing service ReplaceService(new MockUserService()); // Register factory-based services AddService>(serviceType => { return validationType => validationType switch { "email" => new EmailValidator(), "phone" => new PhoneValidator(), _ => new DefaultValidator() }; }); } [Fact] public async Task TestWithMock() { var service = GetRequiredService(); var result = await service.GetUserAsync(Guid.NewGuid()); result.Should().NotBeNull(); _mockRepository.Verify(r => r.GetByIdAsync(It.IsAny()), Times.Once); } } ``` -------------------------------- ### Database Fixture Example in C# Source: https://github.com/paulaolileal/myth/blob/main/Myth.Testing/README.md An example of a TestFixture implementation for managing a shared in-memory database. It configures the database context, seeds initial data, and provides methods for data manipulation and cleanup within tests. ```csharp public class DatabaseFixture : TestFixture { public const string DatabaseName = "TestDatabase"; protected override void ConfigureServices(IServiceCollection services) { services.AddDbContext(options => options.UseInMemoryDatabase(DatabaseName) .EnableSensitiveDataLogging()); services.AddTransient(); services.AddLogging(); } public UserDbContext GetContext() => GetRequiredService(); public async Task SeedDataAsync() { var context = GetContext(); if (!await context.Users.AnyAsync()) { var users = new List(); for (int i = 0; i < 10; i++) { users.Add(new UserEntity { Name = Faker.Name.FullName(), Email = Faker.Internet.Email(), IsActive = true, CreatedAt = DateTime.UtcNow }); } await context.Users.AddRangeAsync(users); await context.SaveChangesAsync(); } } public async Task CleanDataAsync() { var context = GetContext(); context.Users.RemoveRange(context.Users); await context.SaveChangesAsync(); } } // Collection definition for sharing across test classes [CollectionDefinition("Database Collection")] public class DatabaseCollection : ICollectionFixture { // This class has no code, and is never created. // Its purpose is simply to be the place to apply [CollectionDefinition] and all the ICollectionFixture<> interfaces. } ``` -------------------------------- ### MythServiceProvider Initialization and Usage (C#) Source: https://github.com/paulaolileal/myth/blob/main/SKILL.md Demonstrates the initialization and usage of the MythServiceProvider for managing global service providers. It covers initializing, checking initialization status, retrieving required providers, handling fallback providers, and resetting the service provider for testing purposes. This is crucial for dependency injection and service location within the application. ```csharp // Initialize (done automatically by BuildApp/BuildWithGlobalProvider) MythServiceProvider.Initialize(serviceProvider); // Check if initialized if (MythServiceProvider.IsInitialized) { var current = MythServiceProvider.Current; } // Get required (throws if not initialized) var provider = MythServiceProvider.GetRequired(); // Get with fallback var provider = MythServiceProvider.GetOrFallback(fallbackProvider); // Reset (for testing) MythServiceProvider.Reset(); ``` -------------------------------- ### ASP.NET Core Application Setup with Myth Source: https://github.com/paulaolileal/myth/blob/main/CLAUDE.md Demonstrates how to configure an ASP.NET Core application to automatically initialize cross-library dependency resolution using Myth's `BuildApp()` extension method. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddFlow(); builder.Services.AddGuard(); builder.Services.AddFlowActions(config => { ... }); var app = builder.BuildApp(); // Instead of builder.Build() app.UseGuard(); app.Run(); ```