MemoryInspector 1.0.0

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

MemoryInspector

๐Ÿ” Memory monitoring and diagnostics for ASP.NET Core applications
๐Ÿ“Š Exposes /memoryz endpoint with heap usage, GC info, loaded assemblies, and thread count
โšก Real-time memory insights for performance monitoring and debugging

๐Ÿš€ Features

โœ… Heap Usage Monitoring - Track Gen 0, Gen 1, Gen 2, and Large Object Heap
๐Ÿง  GC Information - Garbage collection statistics and settings
๐Ÿ“ฆ Assembly Tracking - List all loaded assemblies with sizes
๐Ÿงต Thread Monitoring - Thread count and thread pool information
๐Ÿ’ป System Metrics - CPU usage, memory usage, and system information
๐Ÿ”ง Easy Integration - Simple extension methods for ASP.NET Core

๐Ÿ“ฆ Installation

dotnet add package MemoryInspector

๐ŸŽฏ Quick Start

Basic Usage

using MemoryInspector;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseRouting();

// Add memory inspector endpoint
app.MapEndpoints(endpoints =>
{
    endpoints.MapMemoryInspector();
});

app.Run();

Detailed Endpoints

app.MapEndpoints(endpoints =>
{
    endpoints.MapDetailedMemoryInspector();
});

This creates multiple endpoints:

  • GET /memoryz - Complete memory information
  • GET /memoryz/process - Process-specific information
  • GET /memoryz/heap - Heap memory details
  • GET /memoryz/gc - Garbage collection statistics
  • GET /memoryz/assemblies - Loaded assemblies list
  • GET /memoryz/threads - Thread information
  • GET /memoryz/system - System metrics
  • GET /memoryz/formatted - Human-readable memory usage
  • POST /memoryz/force-gc - Force garbage collection

๐Ÿ“– Usage Examples

1. Basic Memory Inspector

app.MapEndpoints(endpoints =>
{
    endpoints.MapMemoryInspector("/memoryz");
});

2. Custom Path

app.MapEndpoints(endpoints =>
{
    endpoints.MapMemoryInspector("/api/memory");
});

3. Simple Memory Usage

app.MapEndpoints(endpoints =>
{
    endpoints.MapSimpleMemoryInspector("/memoryz");
});

4. Custom Inspector

var customInspector = new MemoryInspectorService();
app.MapEndpoints(endpoints =>
{
    endpoints.MapMemoryInspector(customInspector, "/memoryz");
});

5. Programmatic Usage

var inspector = new MemoryInspectorService();

// Get complete memory info
var memoryInfo = inspector.GetMemoryInfo();

// Get specific information
var processInfo = inspector.GetProcessInfo();
var heapInfo = inspector.GetHeapInfo();
var gcInfo = inspector.GetGCInfo();

// Force garbage collection
inspector.ForceGC();

// Get formatted memory usage
var formatted = inspector.GetFormattedMemoryUsage();

๐Ÿ“Š API Response Examples

Complete Memory Information

{
  "timestamp": "2024-01-15T10:30:00.000Z",
  "process": {
    "processId": 12345,
    "processName": "MyApp",
    "startTime": "2024-01-15T09:00:00.000Z",
    "totalProcessorTime": "00:01:30.5000000",
    "userProcessorTime": "00:01:25.2000000",
    "workingSet": 52428800,
    "privateMemorySize": 41943040,
    "virtualMemorySize": 1073741824
  },
  "heap": {
    "totalAllocated": 16777216,
    "totalReserved": 33554432,
    "gen0HeapSize": 4194304,
    "gen1HeapSize": 8388608,
    "gen2HeapSize": 16777216,
    "largeObjectHeapSize": 4194304,
    "memoryLoad": 65.5
  },
  "garbageCollection": {
    "totalCollections": 15,
    "gen0Collections": 10,
    "gen1Collections": 3,
    "gen2Collections": 2,
    "isServerGC": false,
    "gcLatencyMode": "Interactive",
    "lastGCTime": 0
  },
  "assemblies": {
    "totalAssemblies": 45,
    "assemblies": [
      {
        "name": "System.Private.CoreLib",
        "version": "8.0.0.0",
        "location": "C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\8.0.0\\System.Private.CoreLib.dll",
        "size": 12345678
      }
    ]
  },
  "threads": {
    "totalThreads": 12,
    "activeThreads": 8,
    "backgroundThreads": 4,
    "foregroundThreads": 8,
    "threadPool": {
      "availableWorkerThreads": 32767,
      "availableCompletionPortThreads": 1000,
      "maxWorkerThreads": 32767,
      "maxCompletionPortThreads": 1000
    }
  },
  "system": {
    "totalPhysicalMemory": 17179869184,
    "availablePhysicalMemory": 8589934592,
    "totalVirtualMemory": 34359738368,
    "availableVirtualMemory": 17179869184,
    "cpuUsage": 25.5,
    "memoryUsage": 50.0
  }
}

Simple Memory Usage

{
  "timestamp": "2024-01-15T10:30:00.000Z",
  "workingSet": 52428800,
  "privateMemory": 41943040,
  "totalAllocated": 16777216,
  "gen0Size": 4194304,
  "gen1Size": 8388608,
  "gen2Size": 16777216,
  "lohSize": 4194304,
  "threadCount": 12,
  "assemblyCount": 45,
  "cpuUsage": 25.5,
  "memoryUsage": 50.0
}

๐Ÿ” API Reference

Extension Methods

Method Description
MapMemoryInspector(string path = "/memoryz") Maps basic memory inspector endpoint
MapMemoryInspector(IMemoryInspector inspector, string path = "/memoryz") Maps memory inspector with custom inspector
MapDetailedMemoryInspector(string basePath = "/memoryz") Maps detailed memory endpoints
MapSimpleMemoryInspector(string path = "/memoryz") Maps simple memory usage endpoint
MapMemoryInspectorWithPath(string path) Maps memory inspector with custom path
MapMemoryInspectorWithPath(IMemoryInspector inspector, string path) Maps memory inspector with custom inspector and path

IMemoryInspector Interface

Method Description
GetMemoryInfo() Gets comprehensive memory information
GetProcessInfo() Gets process-specific information
GetHeapInfo() Gets heap memory information
GetGCInfo() Gets garbage collection information
GetAssembliesInfo() Gets loaded assemblies information
GetThreadInfo() Gets thread information
GetSystemInfo() Gets system information
ForceGC() Forces garbage collection
GetFormattedMemoryUsage() Gets formatted memory usage string

๐ŸŽจ Advanced Examples

Custom Memory Inspector

public class CustomMemoryInspector : IMemoryInspector
{
    private readonly IMemoryInspector _baseInspector;
    
    public CustomMemoryInspector()
    {
        _baseInspector = new MemoryInspectorService();
    }
    
    public MemoryInfo GetMemoryInfo()
    {
        var info = _baseInspector.GetMemoryInfo();
        
        // Add custom metrics
        var customInfo = new MemoryInfo
        {
            Timestamp = info.Timestamp,
            Process = info.Process,
            Heap = info.Heap,
            GarbageCollection = info.GarbageCollection,
            Assemblies = info.Assemblies,
            Threads = info.Threads,
            System = info.System
        };
        
        return customInfo;
    }
    
    // Implement other interface methods...
}

// Usage
var customInspector = new CustomMemoryInspector();
app.MapEndpoints(endpoints =>
{
    endpoints.MapMemoryInspector(customInspector, "/memoryz");
});

Memory Monitoring Middleware

public class MemoryMonitoringMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IMemoryInspector _inspector;
    
    public MemoryMonitoringMiddleware(RequestDelegate next)
    {
        _next = next;
        _inspector = new MemoryInspectorService();
    }
    
    public async Task InvokeAsync(HttpContext context)
    {
        var startMemory = _inspector.GetMemoryInfo();
        
        await _next(context);
        
        var endMemory = _inspector.GetMemoryInfo();
        var memoryDiff = endMemory.Heap.TotalAllocated - startMemory.Heap.TotalAllocated;
        
        if (memoryDiff > 1024 * 1024) // 1MB threshold
        {
            Console.WriteLine($"Memory increase: {memoryDiff} bytes");
        }
    }
}

// Usage
app.UseMiddleware<MemoryMonitoringMiddleware>();

Health Check Integration

builder.Services.AddHealthChecks()
    .AddCheck<MemoryHealthCheck>("memory");

public class MemoryHealthCheck : IHealthCheck
{
    private readonly IMemoryInspector _inspector;
    
    public MemoryHealthCheck()
    {
        _inspector = new MemoryInspectorService();
    }
    
    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        var memoryInfo = _inspector.GetMemoryInfo();
        var memoryUsage = memoryInfo.System.MemoryUsage;
        
        if (memoryUsage > 90)
        {
            return Task.FromResult(HealthCheckResult.Unhealthy($"High memory usage: {memoryUsage:F1}%"));
        }
        
        if (memoryUsage > 80)
        {
            return Task.FromResult(HealthCheckResult.Degraded($"Elevated memory usage: {memoryUsage:F1}%"));
        }
        
        return Task.FromResult(HealthCheckResult.Healthy($"Memory usage: {memoryUsage:F1}%"));
    }
}

๐Ÿงช Testing Examples

Unit Testing

[Test]
public void GetMemoryInfo_ReturnsValidData()
{
    // Arrange
    var inspector = new MemoryInspectorService();
    
    // Act
    var memoryInfo = inspector.GetMemoryInfo();
    
    // Assert
    Assert.That(memoryInfo.Timestamp, Is.GreaterThan(DateTime.UtcNow.AddMinutes(-1)));
    Assert.That(memoryInfo.Process.ProcessId, Is.GreaterThan(0));
    Assert.That(memoryInfo.Heap.TotalAllocated, Is.GreaterThan(0));
    Assert.That(memoryInfo.Assemblies.TotalAssemblies, Is.GreaterThan(0));
    Assert.That(memoryInfo.Threads.TotalThreads, Is.GreaterThan(0));
}

Integration Testing

[Test]
public async Task MemoryInspectorEndpoint_ReturnsValidJson()
{
    // Arrange
    var builder = WebApplication.CreateBuilder();
    var app = builder.Build();
    
    app.MapEndpoints(endpoints =>
    {
        endpoints.MapMemoryInspector("/test-memory");
    });
    
    var client = app.CreateClient();
    
    // Act
    var response = await client.GetAsync("/test-memory");
    var content = await response.Content.ReadAsStringAsync();
    
    // Assert
    Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
    Assert.That(content, Is.Not.Empty);
    
    var memoryInfo = JsonSerializer.Deserialize<MemoryInfo>(content);
    Assert.That(memoryInfo, Is.Not.Null);
    Assert.That(memoryInfo.Process.ProcessId, Is.GreaterThan(0));
}

๐Ÿ”ง Configuration

The package works out of the box with sensible defaults. No configuration required!

Optional: Custom Inspector

// Create a custom inspector for advanced scenarios
var customInspector = new MemoryInspectorService();

// Use the custom inspector in your endpoints
app.MapEndpoints(endpoints =>
{
    endpoints.MapMemoryInspector(customInspector, "/memoryz");
});

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

๐Ÿ“„ License

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

๐Ÿ†˜ Support

  • ๐Ÿ“ง Email: asajjad308@gmail.com

๐Ÿš€ Roadmap

  • Memory leak detection
  • Historical memory tracking
  • Memory profiling integration
  • Custom metrics support
  • Alerting and notifications
  • Memory dump generation
  • Performance counters integration
  • Memory optimization suggestions
  • Real-time memory monitoring
  • Memory usage trends analysis

Made with โค๏ธ for the .NET community

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 was computed.  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.0 150 8/4/2025