Skip to content

Instantly share code, notes, and snippets.

@jdoiwork
Last active June 24, 2020 15:49
Show Gist options
  • Select an option

  • Save jdoiwork/ada40252141d03d327890cc5ab84ee95 to your computer and use it in GitHub Desktop.

Select an option

Save jdoiwork/ada40252141d03d327890cc5ab84ee95 to your computer and use it in GitHub Desktop.
#nullable enable
using System;
using System.Linq;
using Autofac;
using Autofac.Extras.DynamicProxy;
using Castle.DynamicProxy;
using static System.Console;
namespace hello48
{
public class TraceInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
try
{
// show method name and args
var ps = string.Join(", ", invocation.Arguments.Select(x => x.ToString()));
WriteLine("method: {0}({1})", invocation.Method.Name, ps);
// call method
invocation.Proceed();
// show return value
WriteLine("return: {0}",
invocation.ReturnValue ??
(invocation.Method.ReturnType == typeof(void) ?
"(void)" :
"(null)"));
}
catch (System.Exception ex)
{
WriteLine(ex.Message);
throw;
}
}
}
public interface IHoge
{
void Run();
int Plus(int a, int b);
void ErrorOccurred();
}
public class Hoge : IHoge
{
public virtual void Run()
{
WriteLine("hello");
}
public virtual int Plus(int a, int b)
{
return a + b;
}
public virtual void ErrorOccurred()
{
throw new Exception("oh...");
}
}
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<TraceInterceptor>();
builder
.RegisterType<Hoge>()
.As<IHoge>()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(TraceInterceptor));
;
var container = builder.Build();
// var hoge = new Hoge();
var hoge = container.Resolve<IHoge>();
hoge.Run();
hoge.Plus(10, 100);
try
{
hoge.ErrorOccurred();
}
catch (System.Exception ex)
{
WriteLine(ex.ToString());
// throw;
}
}
}
}
$ dotnet run
method: Run()
hello
return: (void)
method: Plus(10, 100)
return: 110
method: ErrorOccurred()
oh...
System.Exception: oh...
at hello48.Hoge.ErrorOccurred() in /workspaces/dotnet48/src/Program.cs:line 63
at Castle.Proxies.Invocations.IHoge_ErrorOccurred.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at hello48.TraceInterceptor.Intercept(IInvocation invocation) in /workspaces/dotnet48/src/Program.cs:line 25
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IHogeProxy.ErrorOccurred()
at hello48.Program.Main(String[] args) in /workspaces/dotnet48/src/Program.cs:line 91
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment