Interceptor.AOP 1.3.11

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

📦 Interceptor.AOP

NuGet NuGet Downloads License: MIT GitHub stars

Descripción general

Una librería ligera y extensible para aplicar Aspect-Oriented Programming (AOP) en aplicaciones .NET, usando interceptores automáticos basados en DispatchProxy.

Ideal para centralizar lógica transversal como reintentos, validaciones, cacheo, auditoría, y manejo de errores sin contaminar la lógica de negocio.

  • Contiene toda la lógica de interceptación (ExceptionInterceptor<T>)
  • Define los atributos como [Audit], [Retry], [Fallback], etc.
  • Se puede usar en cualquier tipo de aplicación .NET: consola, worker, API, etc.
  • Requiere que vos crees el proxy a mano con ProxyFactory.Create<>(). 🔧 Ideal cuando querés máximo control o no estás usando ASP.NET Core con DI tradicional.

🎯 Propósito

Centralizar y estandarizar:

  • 🛡️ Manejo de excepciones con contexto
  • 🔁 Reintentos y circuit breaker con Polly
  • 🧪 Validaciones automáticas con DataAnnotations
  • ⏱️ Medición de tiempo de ejecución
  • 🔐 Cacheo en memoria por método
  • 📝 Auditoría flexible: entrada, salida y errores

🚀 Características

✔️ Soporte para métodos síncronos y asincrónicos (Task, Task<T>)
✔️ Decoración por atributos: fácil de aplicar, simple y expresiva, sin modificar código existente
✔️ Interceptores desacoplados y extensibles ✔️ Soporte para ILogger<T>, IMemoryCache y IOptions<T> ✔️ Ideal para microservicios, APIs, backend robusto ✔️ Integración lista para DI con Interceptor.AOP.AspNetCore

📥 Instalación

Desde NuGet:

  dotnet add package Interceptor.AOP

🧩 Configuración manual (ProxyFactory)

Ejemplo de uconfiguración en Program.cs o Startup.cs

services.AddSingleton(provider =>
{
    var logger = provider.GetRequiredService<ILogger<ProcesarDatosService>>();
    var memoryCache = provider.GetRequiredService<IMemoryCache>();

    // Instancia real del servicio
    var real = new ProcesarDatosService(logger);

    // Proxy con interceptor
    return ProxyFactory.Create<IProcesarDatosService>(
        real,
        logger,
        memoryCache,
        new InterceptorOptions
        {
            EnableRetries = true,
            EnableValidation = true,
            EnableTiming = true
        });
});

Ejemplo de uso de decoradores

public interface IProcesarDatosService
{
    [Audit("ProcesarArchivo", LogInput = true)]
    [Retry(3)]
    [Fallback("FallbackProcesarArchivo")]
    [MeasureTime]
    [Validate]
    [Cache(60)]
    int ProcesarArchivo(int number);

    int FallbackProcesarArchivo(int number);
}

Ejemplo de implementacion

public class ProcesarDatosService : IProcesarDatosService
{
    private readonly ILogger<ProcesarDatosService> _logger;

    public ProcesarDatosService(ILogger<ProcesarDatosService> logger)
    {
        _logger = logger;
    }

    public int ProcesarArchivo(int number)
    {
        _logger.LogInformation("📊 Calculando algo con {number}", number);
        if (number < 0) throw new Exception("Valor negativo no permitido");
        return number * 10;
    }

    public int FallbackProcesarArchivo(int number)
    {
        _logger.LogWarning("⚠️ Fallback ejecutado para {number}", number);
        return -1;
    }
}

📚 Atributos disponibles

Decorador Description
📝 [Audit] Auditoría flexible: entrada, salida y manejo de excepciones con contexto
🔁 [Retry(n)] Reintenta el método n veces si lanza excepción
🛡️ [Fallback("...")] Llama a otro método si el actual falla
⏱️ [MeasureTime] Logea cuánto tarda la ejecución del método
🧪 [Validate] Validaciones automáticas con DataAnnotations
🔐 [Cache(n)] Cachea el resultado por n segundos (solo para Task<T> y métodos síncronos)

📝[Audit] - Auditoría flexible

Auditoría avanzada

El atributo [Audit] permite registrar entrada, salida y errores con granularidad y contexto funcional:

Por defecto

[Audit]
public Task<string> ObtenerClientesAsync() { ... }

➡️ Registra entrada, salida y errores automáticamente.

Con contexto funcional

[Audit("ProcesarArchivo")]
public void ProcesarArchivo(string path) { ... }

➡️ Aparece en logs como: 📥 Entrada en ProcesarArchivo 📤 Salida de ProcesarArchivo ❌ Error en ProcesarArchivo (Auditable)

Auditoría selectiva

[Audit(LogInput = false, LogOutput = false, LogError = true)] // Solo errores
[Audit(Contexto = "Importación", LogOutput = false)] // Entrada + error
[Audit(LogInput = false, LogOutput = true, LogError = false)] // Solo salida

🔁 [Retry(n)] - Reintentos automáticos

Permite reintentar un método si lanza una excepción.

[Retry(3)]
public void ProcesarArchivo() { ... }

➡️ Reintenta hasta 3 veces antes de fallar.

Ideal cuando interactuás con servicios externos, bases de datos o archivos inestables.

🛑 [Fallback("MetodoAlternativo")] - Método alternativo en caso de error

Define un método de respaldo si el original lanza excepción después de los reintentos.

[Fallback("ProcesarArchivoFallback")]
public void ProcesarArchivo() { ... }

public void ProcesarArchivoFallback() { ... }

➡️ Si ProcesarArchivo() falla, se ejecuta ProcesarArchivoFallback() automáticamente.

⏱️ [MeasureTime] - Medición de rendimiento

Registra cuánto tarda en ejecutarse un método.

[MeasureTime]
public void CalcularEstadisticas() { ... }

➡️ Logea automáticamente algo como:

⏱️ CalcularEstadisticas ejecutado en 215ms

🧪 [Validate] - Validación automática

Aplica validaciones usando [Required], [Range], etc. sobre modelos.

[Validate]
public void GuardarCliente(ClienteModel cliente) { ... }

public class ClienteModel
{
    [Required]
    public string Nombre { get; set; }
}

➡️ Si cliente.Nombre es null, lanza ValidationException.

🧠 [Cache(segundos)] - Cache automático en memoria

Guarda el resultado de un método por X segundos.

[Cache(60)]
public async Task<string> ObtenerDatos() => "Desde API";

➡️ Durante 60 segundos, ObtenerDatos() devuelve la misma respuesta (usando IMemoryCache).

⚠️ Solo válido para métodos síncronos o Task<T>. No se aplica a Task (sin retorno).

Author

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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 (1)

Showing the top 1 NuGet packages that depend on Interceptor.AOP:

Package Downloads
Interceptor.AOP.AspNetCore

Integración ASP.NET Core para la librería Interceptor.AOP con soporte automático de interceptores AOP en servicios.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.3.11 132 5/1/2025
1.3.10 138 5/1/2025
1.3.9 136 5/1/2025
1.3.8 168 4/22/2025
1.3.7 151 4/22/2025
1.3.6 156 4/22/2025
1.2.6 205 4/18/2025
1.2.5 191 4/18/2025
1.2.4 193 4/18/2025
1.2.3 185 4/18/2025
1.2.2 189 4/17/2025
1.2.1 191 4/17/2025
1.2.0 185 4/17/2025
1.1.2 201 4/15/2025
1.1.1 190 4/15/2025
1.1.0 196 4/15/2025
1.0.2 194 4/15/2025
1.0.1 207 4/15/2025
1.0.0 191 4/15/2025