Mistruna.Core
1.0.3
dotnet add package Mistruna.Core --version 1.0.3
NuGet\Install-Package Mistruna.Core -Version 1.0.3
<PackageReference Include="Mistruna.Core" Version="1.0.3" />
<PackageVersion Include="Mistruna.Core" Version="1.0.3" />
<PackageReference Include="Mistruna.Core" />
paket add Mistruna.Core --version 1.0.3
#r "nuget: Mistruna.Core, 1.0.3"
#:package Mistruna.Core@1.0.3
#addin nuget:?package=Mistruna.Core&version=1.0.3
#tool nuget:?package=Mistruna.Core&version=1.0.3
Mistruna.Core
Simple SDK for ASP.NET Core with built-in support for MediatR, FluentValidation, JWT authentication, RabbitMQ, and Swagger configuration.
Getting Started • Features • Documentation • Contributing
Features
- 🎯 MediatR Integration - Request/response pipeline with validation and logging behaviors
- ✅ FluentValidation - Built-in request validation pipeline behavior
- 🔐 JWT Authentication - Ready-to-use JWT token handling and policies
- 🐇 RabbitMQ - Message broker integration for microservices communication
- 📚 Swagger/OpenAPI - Pre-configured Swagger setup with versioning support
- ⚠️ Exception Handling - Centralized exception middleware with consistent error responses
- 🏗️ Entity Framework Core - Common patterns and helpers for EF Core
- 🎲 Result Pattern - Functional error handling without exceptions
- 🛡️ Guard Clauses - Defensive programming helpers
- 📦 Value Objects - Email, Phone, Money, Address, DateRange
- 🧩 Domain Events - Event-driven architecture support
- 🔄 Specification Pattern - Encapsulated query logic
Installing Mistruna.Core
You should install Mistruna.Core with NuGet:
Install-Package Mistruna.Core
Or via the .NET CLI:
dotnet add package Mistruna.Core
Using Contracts-Only Package
To reference only the contracts (interfaces) without the full implementation:
Install-Package Mistruna.Core.Contracts
This package is useful when:
- You need interfaces in a separate assembly
- Building shared contract libraries
- Reducing dependencies in client projects
Supported Frameworks
| Framework | Version |
|---|---|
| .NET | 10.0 |
| .NET Standard | 2.0 (Contracts only) |
| .NET Framework | 4.6.2+ (Windows only) |
Usage
Quick Start
Register all core services in one line:
// In Program.cs
builder.Services.AddCore(typeof(Program).Assembly);
// Add middleware
app.UseCoreMiddlewares();
Exception Handling Middleware
Add centralized exception handling to your application:
// In Program.cs or Startup.cs
app.UseMiddleware<ExceptionHandlingMiddleware>();
The middleware automatically handles:
ValidationException→ HTTP 400NotFoundException→ HTTP 404UnauthorizedAccessException→ HTTP 401ForbiddenAccessException→ HTTP 403ConflictException→ HTTP 409TimeoutException→ HTTP 408
Request Validation with MediatR
Register the validation behavior:
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationBehavior<,>));
Create validators for your requests:
public class CreateUserCommandValidator : AbstractValidator<CreateUserCommand>
{
public CreateUserCommandValidator()
{
RuleFor(x => x.Email).NotEmpty().EmailAddress();
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
}
}
Custom Exceptions
Use the built-in exceptions for consistent error handling:
// Not Found with factory method
throw NotFoundException.For<User>(userId);
// Conflict with field info
throw ConflictException.ForField<User>("Email", email);
// Forbidden with role check
throw ForbiddenAccessException.ForRole("Admin");
// Bad Request
throw new BadRequestException("INVALID_INPUT", "Invalid input data");
Result Pattern
Use Result<T> for functional error handling:
public Result<User> GetUser(int id)
{
var user = _repository.Find(id);
if (user is null)
return Result<User>.Failure(Error.NotFound("User.NotFound", $"User {id} not found"));
return Result<User>.Success(user);
}
// Usage with pattern matching
var result = GetUser(1);
return result.Match(
onSuccess: user => Ok(user),
onFailure: error => NotFound(error.Message)
);
// Chaining operations
var result = GetUser(1)
.Map(user => user.Email)
.Bind(email => ValidateEmail(email))
.Tap(email => _logger.Log($"Valid email: {email}"));
Guard Clauses
Defensive programming made easy:
public void CreateUser(string name, string email, int age)
{
Guard.AgainstNullOrEmpty(name, nameof(name));
Guard.AgainstInvalidEmail(email, nameof(email));
Guard.AgainstNegative(age, nameof(age));
Guard.AgainstOutOfRange(age, 0, 150, nameof(age));
// Continue with valid data...
}
Value Objects
Use built-in value objects for common types:
// Email
var email = Email.Create("user@example.com");
// Phone Number
var phone = PhoneNumber.Create("+1 (555) 123-4567");
// Money with currency
var price = Money.Create(99.99m, "USD");
var total = price * 3;
// Address
var address = Address.Create(
street: "123 Main St",
city: "New York",
postalCode: "10001",
country: "USA",
state: "NY"
);
// Date Range
var range = DateRange.Create(DateTime.Today, DateTime.Today.AddDays(7));
if (range.Contains(DateTime.Now)) { /* ... */ }
Entity Base Classes
Use base classes for your domain entities:
// Simple entity with Guid ID
public class User : Entity
{
public string Name { get; set; }
}
// Auditable entity with timestamps
public class Order : AuditableEntity
{
public decimal Total { get; set; }
// CreatedAt, CreatedBy, ModifiedAt, ModifiedBy included
}
// Soft-deletable entity
public class Product : SoftDeletableEntity
{
public string Name { get; set; }
// IsDeleted, DeletedAt, DeletedBy included
// Use Delete() and Restore() methods
}
Specification Pattern
Encapsulate query logic:
public class ActiveUsersSpec : Specification<User>
{
public ActiveUsersSpec()
{
AddCriteria(u => u.IsActive);
AddInclude(u => u.Orders);
ApplyOrderBy(u => u.LastLoginDate);
}
}
// Usage
var spec = new ActiveUsersSpec();
var users = await _repository.FindAsync(spec);
Extension Methods
Rich set of utility extensions:
// Collections
users.IsNullOrEmpty();
items.Batch(100); // Split into chunks
list.ForEach(x => Process(x));
// Strings
"HelloWorld".ToSnakeCase(); // "hello_world"
"secret@email.com".Mask(3, 4); // "sec*********\.com"
text.Truncate(50);
// DateTime
date.StartOfMonth();
date.IsWeekend();
date.AddBusinessDays(5);
date.ToRelativeTime(); // "2 hours ago"
Expression Helpers
Dynamic sorting support for LINQ queries:
var sortExpression = ExpressionHelpers.GetSortLambda<User>("LastName");
var sortedUsers = users.AsQueryable().OrderBy(sortExpression);
API Versioning
Configure API versioning with Swagger support:
services.AddApiVersioningConfiguration();
services.AddSwaggerConfiguration();
Building from Source
Prerequisites
- .NET 10.0 SDK or later
Build
# Restore and build
./Build.ps1
# Build contracts only
./BuildContracts.ps1
# Push to NuGet (requires API key)
./Push.ps1 -ApiKey "your-api-key"
Project Structure
Mistruna.Core/
├── src/
│ ├── Mistruna.Core/ # Main library
│ │ ├── Base/ # Base types and responses
│ │ ├── Enums/ # Common enumerations
│ │ ├── Errors/ # Error handling utilities
│ │ ├── Exceptions/ # Custom exceptions
│ │ ├── Extensions/ # Extension methods
│ │ ├── Filters/ # MVC filters and behaviors
│ │ ├── Helpers/ # Utility helpers
│ │ ├── Microservices/ # Microservices infrastructure
│ │ ├── Middlewares/ # ASP.NET Core middlewares
│ │ └── Providers/ # Test providers
│ └── Mistruna.Core.Contracts/ # Interfaces and contracts
├── test/
│ └── Mistruna.Core.Tests/ # Unit tests
├── samples/ # Usage examples
└── assets/ # Logo and assets
Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgements
Built with:
- MediatR - Simple mediator implementation
- FluentValidation - Validation library
- Swashbuckle - Swagger/OpenAPI tooling
| Product | Versions 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. |
-
net10.0
- Asp.Versioning.Mvc.ApiExplorer (>= 8.1.1)
- FluentValidation (>= 12.1.1)
- MediatR (>= 13.1.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.2)
- Microsoft.AspNetCore.Mvc.NewtonsoftJson (>= 10.0.2)
- Microsoft.EntityFrameworkCore (>= 10.0.2)
- Microsoft.EntityFrameworkCore.SqlServer (>= 10.0.2)
- Mistruna.Core.Contracts (>= 1.0.3)
- Newtonsoft.Json (>= 13.0.4)
- RabbitMQ.Client (>= 6.8.1)
- StackExchange.Redis (>= 2.8.41)
- Swashbuckle.AspNetCore (>= 6.4.0)
- Swashbuckle.AspNetCore.Filters (>= 7.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.