Foundation.Base 2.0.4

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

Foundation - .NET Foundation Library

.NET 10.0 Entity Framework Core FluentValidation SOLID Clean Architecture

⚠️ IMPORTANT: This project is configured for .NET 10.0 and must remain on this version. See .NET Version Policy for details.

📋 Overview

Foundation is a .NET library that provides a solid and reusable foundation for developing applications following SOLID principles, Clean Architecture, and Domain-Driven Design (DDD) patterns. This library implements fundamental patterns such as Repository Pattern, Unit of Work, and provides base classes for entities with built-in audit and validation functionality.

The library is organized into separate projects with clear separation of concerns:

  • Foundation.Domain - Pure domain logic with no dependencies
  • Foundation.Application - Application interfaces and use cases
  • Foundation.Infrastructure - Infrastructure implementations (EF Core, Redis)
  • Foundation.Base - Backward compatibility facade

🏗️ Architecture

The library follows Clean Architecture and SOLID principles with clear separation of concerns:

src/
├── Foundation.Domain/           # Pure domain (no dependencies)
│   ├── Common/                  # Entity base class
│   └── Interfaces/              # Domain contracts
├── Foundation.Application/      # Application layer (depends on Domain)
│   ├── Interfaces/              # Repository, UnitOfWork, Redis contracts
│   ├── Common/                  # Validation, Helpers
│   └── Resources/               # Localization
├── Foundation.Infrastructure/   # Infrastructure (depends on Application/Domain)
│   ├── Data/Configurations/     # EF Core configurations
│   ├── Repositories/            # Repository implementations
│   └── Services/Redis/          # Redis service implementation
└── Foundation.Base/             # Backward compatibility facade

📖 Read the full SOLID Architecture documentation

🔧 Technologies Used

  • .NET 10.0 - Main framework
  • Entity Framework Core 10.0 - ORM for data access
  • FluentValidation 12.1.0 - Entity validation
  • Argon2 1.3.1 - Secure password hashing
  • MySQL/MariaDB - Database support (via Pomelo.EntityFrameworkCore.MySql 9.0.0)
  • Redis - Caching support (via StackExchange.Redis 2.10.1)
  • Newtonsoft.Json 13.0.4 - JSON serialization

🚀 Development (Quick Start)

Development Environment Setup

Note: This project requires .NET 10.0 SDK. If not yet available, see .NET Version Policy for guidance.

# 1. Clone the repository
git clone https://github.com/maiconcardozo/Foundation.git
cd Foundation

# 2. Check if .NET 10 SDK is available
dotnet --list-sdks | grep "^10\."

# 3. If .NET 10 SDK is available:
dotnet restore Solution/Foundation.sln
dotnet build Solution/Foundation.sln --configuration Debug
dotnet test Solution/Foundation.sln --configuration Debug

# If .NET 10 SDK is NOT available yet:
# The project is configured and ready. It will build when SDK is released.
# Do NOT downgrade the TargetFramework version.

The project is optimized for local development with Debug as the default configuration:

# Development environment configuration active by default
export ASPNETCORE_ENVIRONMENT=Development
export DOTNET_ENVIRONMENT=Development

# Continuous build during development
dotnet watch build --configuration Debug
  • Visual Studio 2022 (17.8+) with .NET workload
  • Visual Studio Code with C# Dev Kit extension
  • JetBrains Rider 2024.1+

📦 Production Installation

Prerequisites

  • .NET 10.0 SDK (when available)
  • Entity Framework Core 10.0

Note: See .NET Version Policy for SDK availability information.

Using NuGet Package Manager

# In development - will be published to NuGet
dotnet add package Foundation.Base

Cloning and building locally

git clone https://github.com/maiconcardozo/Foundation.git
cd Foundation
dotnet build Solution/Foundation.sln

🚀 Quick Usage

✨ New Architecture: The library now follows SOLID principles with separate projects. You can use the new namespaces or continue using Foundation.Base for backward compatibility.

using Foundation.Application;
using Foundation.Infrastructure;
using Microsoft.Extensions.DependencyInjection;

// In Program.cs or Startup.cs
builder.Services.AddApplicationServices();    // Register application services
builder.Services.AddInfrastructureServices(); // Register repositories, UnitOfWork, Redis

// Configure DbContext
builder.Services.AddDbContext<YourDbContext>(options =>
{
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});

1. Creating an Entity

// New (recommended)
using Foundation.Domain.Common;

// Old (still works via type forwarding)
// using Foundation.Base.Domain.Implementation;

public class User : Entity
{
    public string Name { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
    
    // Development properties for debugging
    #if DEBUG
    public string? DebugInfo => $"ID: {Id}, Created: {CreatedAt:yyyy-MM-dd HH:mm}";
    #endif
}

2. Configuring Entity Framework (Development)

// New (recommended)
using Foundation.Infrastructure.Data.Configurations;

// Old (still works via type forwarding)
// using Foundation.Base.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public class UserMap : EntityMap<User>
{
    public override void Configure(EntityTypeBuilder<User> builder)
    {
        base.Configure(builder); // Apply base configurations
        
        builder.ToTable("Users");
        builder.Property(x => x.Name).HasMaxLength(100).IsRequired();
        builder.Property(x => x.Email).HasMaxLength(255).IsRequired();
        builder.HasIndex(x => x.Email).IsUnique();
        
        #if DEBUG
        // Development-specific configurations
        builder.HasQueryFilter(x => true); // Remove filters for debugging
        #endif
    }
}

// DbContext configuration for development
public class AppDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
        {
            optionsBuilder.EnableSensitiveDataLogging()
                         .EnableDetailedErrors()
                         .LogTo(Console.WriteLine, LogLevel.Debug);
        }
    }
}

3. Implementing a Repository (With Debug)

// New (recommended)
using Foundation.Application.Interfaces.Repositories;
using Foundation.Infrastructure.Repositories;

// Old (still works via type forwarding)
// using Foundation.Base.Repository.Implementation;

public interface IUserRepository : IEntityRepository<User>
{
    User? GetByEmail(string email);
    Task<List<User>> GetUsersForDebugAsync(); // Development-specific method
}

public class UserRepository : EntityRepository<User>, IUserRepository
{
    public UserRepository(DbContext context) : base(context) { }
    
    public User? GetByEmail(string email)
    {
        return SingleOrDefault(u => u.Email == email && u.IsActive);
    }
    
    #if DEBUG
    public async Task<List<User>> GetUsersForDebugAsync()
    {
        // Development-specific method - do not use in production
        return await GetAllAsync(includeInactive: true);
    }
    #endif
}

4. Using Unit of Work (With Development Logging)

// New (recommended)
using Foundation.Application.Interfaces.UnitOfWork;
using Foundation.Infrastructure.Repositories;

// Old (still works via type forwarding)
// using Foundation.Base.UnitOfWork.Implementation;
using Microsoft.Extensions.Logging;

public class UserService
{
    private readonly IUserRepository _userRepository;
    private readonly IBaseUnitOfWork _unitOfWork;
    private readonly ILogger<UserService> _logger;
    
    public UserService(
        IUserRepository userRepository, 
        IBaseUnitOfWork unitOfWork,
        ILogger<UserService> logger)
    {
        _userRepository = userRepository;
        _unitOfWork = unitOfWork;
        _logger = logger;
    }
    
    public async Task<int> CreateUserAsync(User user)
    {
        #if DEBUG
        _logger.LogDebug("Creating user: {Email} at {Time}", 
            user.Email, DateTime.Now);
        #endif
        
        _userRepository.Add(user);
        var result = await _unitOfWork.CommitAsync();
        
        #if DEBUG
        _logger.LogDebug("User created successfully. Affected rows: {Count}", result);
        #endif
        
        return result;
    }
}

// Development configuration in Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        
        // Development-specific configuration
        if (builder.Environment.IsDevelopment())
        {
            builder.Logging.AddConsole();
            builder.Logging.AddDebug();
            builder.Logging.SetMinimumLevel(LogLevel.Debug);
        }
        
        // Service registration for development
        builder.Services.AddDbContext<AppDbContext>(options =>
        {
            var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
            options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
            
            if (builder.Environment.IsDevelopment())
            {
                options.EnableSensitiveDataLogging();
                options.EnableDetailedErrors();
            }
        });
        
        builder.Services.AddScoped<IUserRepository, UserRepository>();
        builder.Services.AddScoped<IBaseUnitOfWork, BaseUnitOfWork>();
        
        var app = builder.Build();
        
        // Development-specific middleware
        if (app.Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI();
        }
        
        app.Run();
    }
}

📚 Main Components

🏛️ Domain Layer

  • IEntity: Base interface for all entities
  • Entity: Abstract class with audit functionality

🗃️ Repository Layer

  • IEntityRepository<T>: Generic interface for repositories
  • EntityRepository<T>: Base implementation with CRUD operations

🔄 Unit of Work

  • IBaseUnitOfWork: Interface for transaction management
  • BaseUnitOfWork: Implementation with transaction support

🛠️ Utilities

  • StringHelper: Functions for password hashing with Argon2
  • ValidationHelper: FluentValidation integration

🔐 Security

The library includes robust security utilities:

// New (recommended)
using Foundation.Application.Common.Helpers;

// Old (still works via type forwarding)
// using Foundation.Base.Util;

// Password hashing with Argon2
string passwordHash = StringHelper.ComputeArgon2Hash("myPassword123");

// Password verification
bool isValidPassword = StringHelper.VerifyArgon2Hash("myPassword123", passwordHash);

✅ Validation

Native integration with FluentValidation:

using FluentValidation;

public class UserValidator : AbstractValidator<User>
{
    public UserValidator()
    {
        RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
        RuleFor(x => x.Email).NotEmpty().EmailAddress();
    }
}

// In controller
var validationResult = await ValidationHelper.ValidateEntityAsync(user, serviceProvider, this);
if (validationResult != null) return validationResult;

🌐 Internationalization

The library supports localization through resources:

// New (recommended)
using Foundation.Application.Resources;

// Old (still works via type forwarding)
// using Foundation.Base.Resource;

string message = ResourceFoundation.ValidatorNotFoundForTheGivenType;

📖 Detailed Documentation

🚀 For Developers (START HERE)

📚 Technical Documentation

🤖 For Contributors and Agents

🎯 Important: The project follows a development-first approach and MUST maintain .NET 10.0. Always start with the Development Guide and .NET Version Policy!

🤝 Contributing

Contributions are welcome! Please read the contributing guide before submitting pull requests.

📄 License

This project is licensed under the MIT License.

👨‍💻 Author

Maicon Cardozo

📞 Support

For questions, suggestions, or to report issues:

  • Open an issue
  • Contact through GitHub

⭐ If this project was useful to you, consider giving the repository a star!

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
3.1.1-rc.1 172 3/13/2026
3.1.0-rc.1 66 3/9/2026
3.0.5-rc.1 64 3/7/2026
3.0.4-rc.1 56 3/7/2026
3.0.3-rc.1 77 3/2/2026
3.0.2-rc.1 60 2/27/2026
3.0.1-rc.1 57 2/27/2026
3.0.0-rc.1 64 2/27/2026
2.1.6-rc.1 57 2/26/2026
2.1.5-rc.1 58 2/26/2026
2.1.4-rc.1 58 2/26/2026
2.1.3-rc.1 60 2/26/2026
2.1.2-rc.1 60 2/26/2026
2.1.1-rc.1 60 2/26/2026
2.1.0-rc.1 58 2/26/2026
2.0.4 488 11/30/2025
2.0.3 374 11/30/2025
2.0.2 372 11/30/2025
2.0.1 222 11/26/2025
2.0.0 304 11/26/2025 2.0.0 is deprecated because it is no longer maintained and has critical bugs.
Loading failed