BaseInterceptors 0.0.7

dotnet add package BaseInterceptors --version 0.0.7
NuGet\Install-Package BaseInterceptors -Version 0.0.7
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="BaseInterceptors" Version="0.0.7" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add BaseInterceptors --version 0.0.7
#r "nuget: BaseInterceptors, 0.0.7"
#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.
// Install BaseInterceptors as a Cake Addin
#addin nuget:?package=BaseInterceptors&version=0.0.7

// Install BaseInterceptors as a Cake Tool
#tool nuget:?package=BaseInterceptors&version=0.0.7

BaseInterceptors

Provides simple base interceptors for a number of everyday interception scenarios like execution timing, method entry/exit logging or exception handling. If you're new to interceptors and realise that implementing them for synchronous and asynchronous methods is more complex than expected, use these base classes to avoid the complexity.

Concept

Implementing an interceptor should be easy, as easy as providing a single method of what to do in case of a certain code aspect. This library helps to do that. Interception scenarios implemented so far:

  • method entry/exit interception
  • method timing interception
  • exception interception

Each scenario is supported by an abstract, base implementation, with the fewest possible overridable methods, i.e. OnCompleted(IInvocation invocation, TimeSpan elapsed) for the timing interceptor. Each interceptor type has 3 base implementations, i.e. TimingInterceptor, TimingInterceptorSync and TimingInterceptorAsync. The implementation called ...Sync exposes a sinlge, synchronous method to override, ...Async exposes a single, async method to override, ... (without a suffix) exposes both a sync and an async method to override. The ...Sync interceptor should be used if the aspect is CPU intensive, ...Async should be used if the aspect is IO intensive - just as picking the sync or async versions of a method. The third (suffix-less) implementation uses sync callbacks for sync intercepted methods and async callbacks for async intercepted methods.

These base interceptors are designed to work in a software envirnment where Castle Windsor is used to manage dependency injection. Interceptors can be applied to classes using the Interceptor attribute. Another approach (using Castle Windsor component registrations with interceptors) is not yet complete.

How to Use

If you need an interceptor, chose one of the base interceptors in this package:

  • to handle exceptions (log them, swallow them, change the return value based on them), start from ExceptionInterceptor
  • to do something on method entry / exit (i.e. log it, check pre-requisites), start from ExecutionInterceptor
  • to measure method execution time (log it, update the response with it), start from TimingInterceptor
  • if you have a different scenario, feel free to use the the source code of those interceptors to implement your own (and let me know about your scenario!)

Let's say, you go with TimingInterceptor.

Now, decide whether you want to implement intercepting code to be sync, async or mixed - use the appropriate implementation of the interceptor you selected above.

Let's say you want to implement your intercepting logic as sync - so you'll derive from TimingInterceptorSync.

Now, create a new class code file and type this much (the bits in italic):

public class MyTimingInterceptor : TimingInterceptorSync

{ override }

Visual Studio will show you the overridables (OnCompleted in this case) - all you need to do is implement those methods (all of them).

That's it, you implemented an interceptor!

Examples

Example 1 - Measure Exceution Time Aspect

Scenario: there is an application with a class, whose methods' execution time needs to be measured and displayed on the console output. The application uses dependency injection (DI) to create instances of this class. The application targets .Net Core 2.2+ or .Net Framework 4.5+. Steps to implement the timing aspect:

  1. Add a reference to the BaseInterceptors package.

  2. Within your application add a new class like this: using BaseInterceptors; using Castle.DynamicProxy; using System;

    namespace DemoApp { /// <summary> /// Implements a TimingInterceptor, that - when a method execution is finished - /// logs execution time to the console. /// </summary> public class LogTimingInterceptor : TimingInterceptorSync { protected override void OnCompleted(IInvocation invocation, TimeSpan executionTime) { string methodName = GetMethodName(invocation); Console.WriteLine($"Timing interceptor: {methodName} execution time: {executionTime.TotalMilliseconds} msecs"); }

        private string GetMethodName(IInvocation invocation)
        {
            return $"{invocation.InvocationTarget.GetType().Name}.{invocation.Method.Name}()";
        }
    }
    

    }

  3. Apply the interceptor to the class [Interceptor(typeof(LogTimingInterceptor))] public class Business : IBusiness { ... }

  4. Add the interceptor to your DI registration code container.Register(Component.For<LogTimingInterceptor>().ImplementedBy<LogTimingInterceptor>().Named(nameof(LogTimingInterceptor)).LifestyleTransient());

... and you're done. Deriving your interceptor from TimingInterceptorSync means that for both sync and async intercepted methods your OnCompleted() method will be invoked in a synchronous fashion. If - instead of outputting a line to the console - you want to log execution time to a remote service using an async API, derive your interceptor from TimingInterceptorAsync, and override the OnCompletedAsync() method.

Example 2 - Method Entry and Exit Logging Aspect

Scenario: there is an application with a class, whose methods' execution (entry and exit) needs to be logged to a remote service using an async API. The application uses dependency injection (DI) to create instances of this class. The application targets .Net Core 2.2+ or .Net Framework 4.5+. Assume that there is a logger, registered as a DI dependency (class Logger that implements ILogger). To implement the logging aspect, steps 1, 3 and 4 are the same as above. In step 2, the interceptor class would look like this: using BaseInterceptors; using Castle.DynamicProxy; using System;

namespace DemoApp
{
    public class LogExecutionInterceptor : ExecutionInterceptorAsync
    {
        private ILogger _logger;
        
        public LogExecutionInterceptor(ILogger logger)
        {
            _logger = logger;
        }
        
        protected override void OnEntryAsync(IInvocation invocation)
        {
            _logger.LogEntry($"Execution interceptor: Entering {GetMethodName(invocation)}");
        }

        protected override void OnExitAsync(IInvocation invocation)
        {
            _logger.LogExit($"Execution interceptor: Exiting {GetMethodName(invocation)}");
        }

        private string GetMethodName(IInvocation invocation)
        {
            return $"{invocation.InvocationTarget.GetType().Name}.{invocation.Method.Name}()";
        }
    }
}

... and you're done.

Example 3 - Exception Handling Aspect

Scenario: there is an application with a class, representing an API, where you need to implement top-level exception handling: all exceptions need to be caught, logged, and translated to a status value of 500 in the API method return value. The application uses dependency injection (DI) to create instances of this class. The application targets .Net Core 2.2+ or .Net Framework 4.5+. Assume that there is a logger, registered as a DI dependency (class Logger that implements ILogger). To implement the logging aspect, steps 1, 3 and 4 are the same as above. In step 2, the interceptor class would look like this: using BaseInterceptors; using Castle.DynamicProxy; using System;

namespace DemoApp
{
    public class LogExceptionInterceptor : ExceptionInterceptorSync
    {
        private ILogger _logger;
        
        public LogExecutionInterceptor(ILogger logger)
        {
            _logger = logger;
        }
        
        protected override object OnException(IInvocation invocation, Exception ex)
        {
            var method = GetMethodName(invocation);
            _logger.Error($"{method} failed.\r\nReturn value: {invocation.ReturnValue}.\r\nException: {ex}");
            // Set method invocation return value to something designating an error.
            var result = (ApiStatus)invocation.ReturnValue;
            result.Status = 500;
            return result;
        }

        private string GetMethodName(IInvocation invocation)
        {
            return $"{invocation.InvocationTarget.GetType().Name}.{invocation.Method.Name}()";
        }
    }
}

We chose to derive our interceptor from ExceptionInterceptorSync, because our logging service is synchronous, and setting the result is not IO intensive. If logging was remote, you'd derive your interceptor from ExceptionInterceptorAsync.

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  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 is compatible.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 is compatible.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net45 is compatible.  net451 was computed.  net452 was computed.  net46 was computed.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos 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
0.0.7 165 6/13/2023
0.0.6 122 6/13/2023
0.0.5 124 6/12/2023
0.0.4 357 7/31/2021
0.0.3 348 7/31/2021
0.0.2 479 3/5/2020
0.0.1 487 2/24/2020

Added support for more dotnet targets: netstandard2.0, net5.0, net6.0 nad net7.0.