Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Created January 14, 2013 13:48
Show Gist options
  • Save akimboyko/4530162 to your computer and use it in GitHub Desktop.
Save akimboyko/4530162 to your computer and use it in GitHub Desktop.
How to intercept method with custom attribute using DynamicProxy
void Main()
{
ProxyGenerator proxyGenerator = CreateProxyGenerator();
IService proxy =
proxyGenerator
.CreateInterfaceProxyWithTargetInterface(new Service() as IService, new TracingInterceptorAspect());
proxy.ProcessRequest();
proxyGenerator.ProxyBuilder.ModuleScope.SaveAssembly(false);
}
public interface IService
{
void ProcessRequest();
}
[Serializable]
public class TracingAttribute : Attribute
{
}
public sealed class Service : IService
{
[Tracing]
public void ProcessRequest()
{
string.Format("{0} call ProcessRequest", GetType().FullName).Dump();
}
}
[Serializable]
public class TracingInterceptorAspect : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var hasAttribute = invocation.MethodInvocationTarget.GetCustomAttribute(typeof(TracingAttribute)) != null;
invocation.Dump();
if(hasAttribute)
{
string.Format("Before {0} call ProcessRequest", invocation.TargetType).Dump();
}
invocation.Proceed();
if(hasAttribute)
{
string.Format("After {0} call ProcessRequest", invocation.TargetType).Dump();
}
}
}
public static ProxyGenerator CreateProxyGenerator()
{
var savePhysicalAssembly = true;
var strongAssemblyName = ModuleScope.DEFAULT_ASSEMBLY_NAME;
var strongModulePath = ModuleScope.DEFAULT_FILE_NAME;
var weakAssemblyName = "Castle.Core.Tracing.Interceptor";
var weakModulePath = "Castle.Core.Tracing.TargetProxy.dll";
var scope = new ModuleScope(savePhysicalAssembly, true, strongAssemblyName, strongModulePath, weakAssemblyName, weakModulePath);
return new ProxyGenerator(new DefaultProxyBuilder(scope));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment