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

About Rodolfo Finochietti

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

Posted on 02/12/2006, in .NET. Bookmark the permalink. Leave a comment.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: