Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Last active December 11, 2015 02:19
Show Gist options
  • Save akimboyko/4530172 to your computer and use it in GitHub Desktop.
Save akimboyko/4530172 to your computer and use it in GitHub Desktop.
How to work with sealed class w/o virtual methods using DynamicProxy
void Main()
{
ProxyGenerator proxyGenerator = CreateProxyGenerator();
IService proxy =
proxyGenerator
// http://kozmic.pl/2009/04/01/castle-dynamic-proxy-tutorial-part-ix-interface-proxy-with-target/
.CreateInterfaceProxyWithTargetInterface(new Service() as IService, new TracingInterceptorAspect());
proxy.ProcessRequest();
proxyGenerator.ProxyBuilder.ModuleScope.SaveAssembly(false);
}
public interface IService
{
void ProcessRequest();
}
// this class is sealed and could not be decorated
public sealed class Service : IService
{
public void ProcessRequest()
{
string.Format("{0} call ProcessRequest", GetType().FullName).Dump();
}
}
[Serializable]
public class TracingInterceptorAspect : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.Dump();
string.Format("Before {0} call ProcessRequest", invocation.TargetType).Dump();
invocation.Proceed();
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));
}
@akimboyko
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment