Skip to content

Instantly share code, notes, and snippets.

@seesharper
Last active October 14, 2019 20:50
Show Gist options
  • Save seesharper/83f310f01f58036d16013c0d82b00856 to your computer and use it in GitHub Desktop.
Save seesharper/83f310f01f58036d16013c0d82b00856 to your computer and use it in GitHub Desktop.
InterceptionDemo
using System;
using LightInject.Interception;
namespace InterceptionDemo
{
class Program
{
static void Main(string[] args)
{
var proxyBuilder = new ProxyBuilder();
// Pass null as the target factory here since we pass the target to the interceptor.
var proxyDefinition = new ProxyDefinition(typeof(IService), () => null);
// "Implement" the proxy type by routing all method calls to SampleInterceptor;
proxyDefinition.Implement(() => new SampleInterceptor(new Duck()));
var proxyType = proxyBuilder.GetProxyType(proxyDefinition);
var proxy = (IService)Activator.CreateInstance(proxyType);
proxy.SomeMethod("42");
proxy.SomeMethod("84");
}
}
public interface IService
{
void SomeMethod(string args);
}
public class Service : IService
{
public Service()
{
}
public void SomeMethod(string args)
{
Console.WriteLine(args);
}
}
public class SampleInterceptor : IInterceptor
{
private readonly object target;
private readonly Type targetType;
public SampleInterceptor(object target)
{
this.target = target;
targetType = target.GetType();
}
public object Invoke(IInvocationInfo invocationInfo)
{
// Do a simple method search on the duck type.
var targetMethod = targetType.GetMethod(invocationInfo.Method.Name);
return targetMethod.Invoke(target, invocationInfo.Arguments);
}
}
public class Duck
{
public void SomeMethod(string args)
{
Console.WriteLine($"Duck called with {args}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment