Created
January 19, 2020 07:39
-
-
Save gsscoder/708e48dd2487f7d84a5975cfc6caa151 to your computer and use it in GitHub Desktop.
Simple C# program that uses Caste DynamicProxy intereception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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