Created
January 14, 2013 13:48
-
-
Save akimboyko/4530162 to your computer and use it in GitHub Desktop.
How to intercept method with custom attribute using DynamicProxy
This file contains hidden or 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
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
https://github.com/akimboyko/AOP.Hydra/blob/master/examples/interceptor/CastleCoreTracingTargetProxyWithAttribute.linq — original LinqPAD file