Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Created January 19, 2020 07:39
Show Gist options
  • Save gsscoder/708e48dd2487f7d84a5975cfc6caa151 to your computer and use it in GitHub Desktop.
Save gsscoder/708e48dd2487f7d84a5975cfc6caa151 to your computer and use it in GitHub Desktop.
Simple C# program that uses Caste DynamicProxy intereception
// requires:
// dotnet add package Castle.Core --version 4.4.0
// output:
// IAdder::Sum invoked
// 3
using System.Runtime.CompilerServices;
using System;
using Castle.DynamicProxy;
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
interface IAdder
{
int Sum(int a, int b);
}
class Adder : IAdder
{
public int Sum(int a, int b) { return a + b; }
}
public class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method.Name.Equals("Sum")) {
Console.WriteLine("IAdder::Sum invoked");
}
invocation.Proceed();
}
}
class Program
{
static void Main(string[] args)
{
IAdder adder = new Adder();
var proxy = new ProxyGenerator().CreateInterfaceProxyWithTarget(adder, new Interceptor());
var result = proxy.Sum(1, 2);
Console.WriteLine($"{result}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment