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” );
}
}