Proxy factory with Dynamic Proxy

In this post Pablo explains how to build a proxy factory similar to FactoryChannel in WCF. Here another implementation using DynamicProxy from Castle Project. The main advantage is that it is not necessary that the parameters of the methods of the interface implement MarshalByRefObject (if the parameters are not value types).

using System;
using Castle.DynamicProxy;

public class MyProxy<T> where T : class
public MyProxy( ) { }

public T BuildProxy( )
ProxyGenerator generator = new ProxyGenerator( );

      object proxy = generator.CreateProxy( typeof( T ), new Interceptor( ), null );

      return proxy as T;

public class Interceptor
public object Intercept( IInvocation invocation, params object[] args )
Console.WriteLine( “Calling to the method:” );
Console.WriteLine( “\Name: {0}”, invocation.Method.Name );

      //Place remote service call here
return null;

public class Factory<T>
public Factory( ) { }

   public T Create( )
MyProxy<IMyService> proxy = new MyProxy<IMyService>( );
return proxy.BuildProxy( );

public interface IMyService
void HelloWorld( string message );

public class Program
static void Main(string[] args)
Factory<IMyService> factory = new Factory<IMyService>( );
IMyService service = factory.Create( );
service.HelloWorld( “Rodolfo” );


Rodolfo Finochietti View All →

Uma's and Gino's father, and a programmer ;)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: