Look Ma! Real Proxies...

Wednesday, December 03, 2008 3:56:17 PM (Mountain Standard Time, UTC-07:00)

I took some time today to pull down the source code for SvnBridge today, and man, I was blown away. I started at Program.cs and made it to line 25 Bootstrapper.Start(). From there I went on to look at the hand rolled container, then the ProxyFactory.

In order for me to fully grasp the System.Runtime.Remoting API for creating proxies I had to re-write the code from SVN Bridge.... I just had too... it's just how I learn. It's like tracing over cartoons when you're a kid. I still do it!

In case you're interested, the attached code is the sample I put together that is derived from the source code of SvnBridge. If you haven't checked out the source for the project, you really should.

Pretty cool stuff.... Hopefully, this helps out anyone else who's just as curious

My reduced sample source code...

private static void Main(string[] args)
{
    var marshal_mathers = new Person("marshall mathers");
    var some_celebrity = ProxyFactory.Create<IPerson>(marshal_mathers, new MyNameIsSlimShadyInterceptor());
 
    try
    {
        var name = some_celebrity.what_is_your_name();
        name.should_be_equal_to("slim shady");
    }
    catch (Exception e)
    {
        Console.Out.WriteLine(e);
    }
    Console.Out.WriteLine("will the real slim shady please stand up...");
    Console.In.ReadLine();
}

#

Container Configuration

Sunday, November 09, 2008 8:19:45 PM (Mountain Standard Time, UTC-07:00)

In my last post I briefly mentioned how we were wiring some components in to our container.  The syntax looked like the following:

            container.AddProxyOf(
                new ReportPresenterTaskConfiguration(), 
                new ReportPresenterTask(
                    Lazy.Load<IReportDocumentBuilder>(),
                    Lazy.Load<IApplicationSettings>())
                    );

We're using Castle Windsor under the hood, but we have an abstraction over it that allows us to configure it as we like. Even switching the underlying implementation. Which we did, from our hand rolled container to Castle Windsor. The implementation of the above method looks as follows:

        public void AddProxyOf<Interface, Target>(IProxyConfiguration<Interface> configuration, Target instance)
            where Target : Interface
        {
            var builder = new ProxyBuilder<Interface>();
            configuration.Configure(builder);
            AddInstanceOf(builder.CreateProxyFor(instance));
        }

Wikipedia defines the Proxy design pattern as:

A proxy, in its most general form, is a class functioning as an interface to another thing.

To understand the ProxyBuilder<Interface> implementation you can checkout JP's strongly typed selective proxies. The "AddProxyOf" method creates an instance of a proxybuilder. It then passes it to the configuration to allow it to configure the proxy builder before building the proxy. Then it registers the proxy as a singleton in to the container.

    public interface IConfiguration<T>
    {
        void Configure(T item_to_configure);
    }
    public interface IProxyConfiguration<T> : IConfiguration<IProxyBuilder<T>>
    {
    }

In this case the proxy configuration looks like:

    public class ReportPresenterTaskConfiguration : IProxyConfiguration<IReportPresenterTask>
    {
        public void Configure(IProxyBuilder<IReportPresenterTask> builder)
        {
            var constraint = builder.AddInterceptor<DisplayProgressBarInterceptor>();
            constraint.InterceptOn.RetrieveAuditReport();
        }
    }

This guy adds a progress bar interceptor, that displays a progress bar as the report is getting generated via the "RetrieveAuditReport" method on the IReportPresenterTask.

#

Lazy Loaded Interceptors

Sunday, November 09, 2008 2:55:32 PM (Mountain Standard Time, UTC-07:00)

Patterns of Enterprise Application Architecture defines Lazy Load as:

An object that doesn't contain all of the data you need but knows how to get it.

 

A while back I was trying to figure out how to lazy load objects from a container, so that I didn't need to depend on the objects dependencies needing to be wired up in the correct order. The syntax I was looking for was something like the following....

container.AddProxyOf(
    new ReportPresenterTaskConfiguration(),
    new ReportPresenterTask(
        Lazy.Load<IReportDocumentBuilder>(),
        Lazy.Load<IApplicationSettings>())
    );

Lazy.Load<T> will return a proxy in place of an actual implementation. This is just a temporary place holder that will forward the calls to the actual implementation. It wont load an instance of the actual type until the first time a call is made to it.

public class when_calling_a_method_with_no_arguments_on_a_lazy_loaded_proxy : lazy_loaded_object_context
{
    [Observation]
    public void should_forward_the_original_call_to_the_target()
    {
        target.should_have_been_asked_to(t => t.OneMethod());
    }

    protected override void establish_context()
    {
        target = dependency<ITargetObject>();

        test_container
            .setup_result_for(t => t.find_an_implementation_of<ITargetObject>())
            .will_return(target)
            .Repeat.Once();
    }

    protected override void because_of()
    {
        var result = Lazy.Load<ITargetObject>();
        result.OneMethod();
    }

    private ITargetObject target;
}

So when the method "OneMethod" is called on the proxy. It should forward the call to the target, which can be loaded from the container. The implementation depends on Castle DynamicProxy, and looks like the following...

public static class Lazy
{
    public static T Load<T>() where T : class
    {
        return create_proxy_for<T>(create_interceptor_for<T>());
    }

    private static LazyLoadedInterceptor<T> create_interceptor_for<T>() where T : class
    {
        Func<T> get_the_implementation = resolve.dependency_for<T>;
        return new LazyLoadedInterceptor<T>(get_the_implementation.memorize());
    }

    private static T create_proxy_for<T>(IInterceptor interceptor)
    {
        return new ProxyGenerator().CreateInterfaceProxyWithoutTarget<T>(interceptor);
    }
}

internal class LazyLoadedInterceptor<T> : IInterceptor
{
    private readonly Func<T> get_the_implementation;

    public LazyLoadedInterceptor(Func<T> get_the_implementation)
    {
        this.get_the_implementation = get_the_implementation;
    }

    public void Intercept(IInvocation invocation)
    {
        var method = invocation.GetConcreteMethodInvocationTarget();
        invocation.ReturnValue = method.Invoke(get_the_implementation(), invocation.Arguments);
    }
}

public static class func_extensions
{
    public static Func<T> memorize<T>(this Func<T> item) where T : class
    {
        T the_implementation = null;
        return () => {
                   if (null == the_implementation) {
                       the_implementation = item();
                   }
                   return the_implementation;
               };
    }
}

"resolve" is a static gateway to the underlying IDependencyRegistry. This idea was totally inspired by JP's strongly typed selective proxies. If you haven't already, you should definitely check it out.

Download the source.

#

The Identity Map

Tuesday, December 18, 2007 12:21:21 PM (Mountain Standard Time, UTC-07:00)

This week while I'm at home on holidays, I've been reading...

Patterns of Enterprise Application Architecture (The Addison-Wesley Signature Series)
by Martin Fowler

Read more about this title...

This book is amazing, I could probably read it over and over again. The patterns that it presents makes a lot of sense, the actual implementations and examples could probably re-vamped but I'm finding that it's a great starter to trying to understand the concepts.

So today I'm trying to grok this concept of the "IDENTITY MAP". The book defines it as:

"Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them."

I put together a quick implementation that I'm using for an assignment I'm writing for school. I'm creating repositories that have 2 dependencies. First dependency is a Data Mapper (not to be confused with a Mapper) and the second is an Identity Map.

As objects are requested from the repository, the repository is checking the identity map to see if an instance has been loaded, if it has it's immediately returned to the caller. If the object is not in the map the repository leverages the data mapper to load the object, then adds it to the map and returns it to the caller.

The Data Mapper is defined as:

"A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself." - PoEAA

I created a Layer Supertype to register objects in the map. The Domain Layer Super type demands that domain objects had an ID. The ID is what's getting used to load and register objects into the map.

The Layer Supertype is defined as:

"A type that acts as a the supertype for all types in it's layer." - PoEAA

The Domain Layer Super Type.

    public interface IDomainObject {
        long ID();
    }

My actual implementation of the identity map looks like this...

    public class IdentityMap< T > : IIdentityMap< T > where T : IDomainObject {
        public IdentityMap() {
            _items = new List< T >( );
        }

        public void Add( T domainObject ) {
            EnsureObjectHasNotAlreadyBeenAdded( domainObject );
            _items.Add( domainObject );
        }

        public T FindObjectWithIdOf( long idOfObjectToFind ) {
            foreach ( T item in _items ) {
                if ( item.ID( ).Equals( idOfObjectToFind ) ) {
                    return item;
                }
            }
            return default( T );
        }

        private void EnsureObjectHasNotAlreadyBeenAdded( T domainObject ) {
            if ( ContainsObjectWithIdOf( domainObject.ID( ) ) ) {
                throw new ObjectAlreadyAddedToIdentityMapException( domainObject );
            }
        }

        private readonly IList< T > _items;
    }

One of the benefits I like about the Identity Map is that it acts as an in memory cache for objects loaded from the database. This reduces the number of trips to and from the persistence store.

Source Code

#

Returning the Default on Generic Types

Friday, May 18, 2007 2:37:24 AM (Mountain Standard Time, UTC-07:00)

So during my quest to understand NHibernate I came across a new keyword in C#. (well kind of new, it's actually an old keyword but used in a different manner specifically for generic types.)

Here's my problem... When you define a generic type it does not assume it to be either of a reference type or value type. And I do not want to force my type to be a reference type, I want it to be generic. But in a scenario where I have to return an blank or "null" value, that assumption says that the type has to be a reference type...

Here's what I'm talking about:



The return null statement is making the assumption that T is a reference type. (I don't want to make this assumption!) In this case I would like to return the default value for reference types and value types without having to create 2 generic types. One for each!

So I can use the default( T ) statement which will return a null for reference types, and a 0 for value types! Problem solved.

        public T SearchFor( Int32 id ) {
            using( ISessionTransaction dbStore = _manager.StartTransaction( ) ) {
                try {
                    return ( T )dbStore.Session.Load( typeof( T ), id );
                }
                catch( ObjectNotFoundException ) {
                    return default( T );
                }
                catch( ADOException ) {
                    if( dbStore != null && null != dbStore.Transaction ) {
                        dbStore.Transaction.Rollback( );
                    }
                    throw;
                }
            }
        }


See MSDN for more information... http://msdn2.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx

#