<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Innovatian Software &#187; Patterns</title>
	<atom:link href="http://innovatian.com/category/patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://innovatian.com</link>
	<description></description>
	<lastBuildDate>Sat, 12 Nov 2011 16:40:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Weak Proxy Factory</title>
		<link>http://innovatian.com/2009/08/weak-proxy-factory-2/</link>
		<comments>http://innovatian.com/2009/08/weak-proxy-factory-2/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 00:35:18 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://disassembla.net/blog/?p=119</guid>
		<description><![CDATA[In the previous article I showed how one could construct a weak proxy object using LinFu. This idea very slick, but it doesn&#8217;t do us much good unless there is something built around it. DISCLAIMER: Blocks of this code are taken directly from the Ninject 2.0 source base and re-purposed. All code in this article [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>In the previous article I showed how one could construct a weak proxy object using LinFu. This idea very slick, but it doesn&#8217;t do us much good unless there is something built around it.</p>
<p>DISCLAIMER: Blocks of this code are taken directly from the Ninject 2.0 source base and re-purposed. All code in this article is released under the same licenses as the source works (Apache 2 and MS-PL).</p>
<p>To start, we have IWeakCache (formerly <a href="http://github.com/enkari/ninject/blob/de9a243fc8eff2aeb91cd763db5dcdcd5bd6fe74/src/Ninject/Activation/Caching/ICache.cs">ICache.cs</a>) and <a href="http://github.com/enkari/ninject/blob/de9a243fc8eff2aeb91cd763db5dcdcd5bd6fe74/src/Ninject/Activation/Caching/ICachePruner.cs">ICachePruner</a> to describe our cache backing and the cleanup strategy. The IWeakCache is like the Ninject ICache except that I don&#8217;t provide the Get method and it takes a Weak<Weakinterceptor<T>> pointer and the source object. We can watch the weak reference for cleanup and execute it on the original object.</p>
<pre>    public interface IWeakCache
    {
        void Remember&lt;T&gt;( Weak&lt;WeakInterceptor&lt;T&gt;&gt; reference, T instance );

        void Prune();

        void Clear();
    }

    public interface ICachePruner
    {
        void Start( IWeakCache cache );

        void Stop();
    }</pre>
<p>I use the <a href="http://github.com/enkari/ninject/blob/de9a243fc8eff2aeb91cd763db5dcdcd5bd6fe74/src/Ninject/Activation/Caching/GarbageCollectionCachePruner.cs">GarbageCollectionCachePruner</a> directly from Ninject but change the ICache and ICachePruner interfaces to my own.</p>
<p>Given that I need to create my own cache to monitor weak references, I modified the <a href="http://github.com/enkari/ninject/blob/de9a243fc8eff2aeb91cd763db5dcdcd5bd6fe74/src/Ninject/Activation/Caching/Cache.cs">Cache.cs</a> file to accommodate this.</p>
<pre>    public class WeakProxyCache : IDisposable, IWeakCache
    {
        private readonly Multimap&lt;Type, CacheEntry&gt; _entries = new Multimap&lt;Type, CacheEntry&gt;();

        #region Implementation of IWeakCache

        public void Remember&lt;T&gt;( Weak&lt;WeakInterceptor&lt;T&gt;&gt; reference, T instance )
        {
            lock ( _entries )
            {
                CacheEntry entry = CacheEntry.FromObject( reference, instance );
                _entries[entry.Service].Add( entry );
            }
        }

        public void Prune()
        {
            lock ( _entries )
            {
                List&lt;CacheEntry&gt; expiredValues = _entries
                    .SelectMany( entry =&gt; entry.Value )
                    .Where( item =&gt; !item.Scope.IsAlive )
                    .ToList();
                expiredValues.ForEach( Forget );
            }
        }

        public void Clear()
        {
            lock ( _entries )
            {
                _entries
                    .SelectMany( e =&gt; e.Value )
                    .ToList()
                    .ForEach( entry =&gt; _entries[entry.Service]
                                           .Remove( entry ) );
            }
        }

        #endregion

        private void Forget( CacheEntry entry )
        {
            _entries[entry.Service].Remove( entry );
            var disposable = entry.Instance as IDisposable;
            if ( disposable != null )
            {
                disposable.Dispose();
            }
        }

        #region Implementation of IDisposable

        protected bool IsDisposed { get; private set; }

        public void Dispose()
        {
            Dispose( true );
            GC.SuppressFinalize( this );
        }

        public void Dispose( bool disposing )
        {
            if ( disposing &amp;amp;&amp;amp; !IsDisposed )
            {
                Clear();
                IsDisposed = true;
            }
        }

        #endregion

        #region Nested type: CacheEntry

        protected class CacheEntry
        {
            public WeakReference Scope { get; private set; }
            public Type Service { get; private set; }
            public object Instance { get; private set; }

            public static CacheEntry FromObject&lt;T&gt;( WeakReference reference, T instance )
            {
                return new CacheEntry
                       {
                           Scope = reference,
                           Instance = instance,
                           Service = typeof (T)
                       };
            }
        }

        #endregion
    }</pre>
</p>
<p>With this, I now have everything I need to create my WeakProxyFactory. I set up the .ctor to take an IWeakCache and ICachePruner so that we can adjust the storage and cleanup as needed. In this class, I am actually using the CommonServiceLocator to get the real object instance.</p>
<pre>    public class WeakProxyFactory
    {
        private readonly IWeakCache _defaultProxyCache;
        private readonly ICachePruner _defaultProxyCachePruner;
        private readonly ProxyFactory _proxyFactory;

        public WeakProxyFactory()
            : this( new WeakProxyCache(), new GarbageCollectionCachePruner() )
        {
        }

        public WeakProxyFactory( IWeakCache cache, ICachePruner cachePruner )
        {
            _proxyFactory = new ProxyFactory();
            _defaultProxyCache = cache;
            _defaultProxyCachePruner = cachePruner;
            _defaultProxyCachePruner.Start( _defaultProxyCache );
        }

        public virtual T GetProxy&lt;T&gt;()
        {
            var instance = GetInstance&lt;T&gt;();

            T proxy = WrapInstance( instance );

            return proxy;
        }

        protected virtual T WrapInstance&lt;T&gt;( T instance )
        {
            var weakReference = new Weak&lt;WeakInterceptor&lt;T&gt;&gt;(
                new WeakInterceptor&lt;T&gt;(
                    new Weak&lt;T&gt;( instance ) ) );

            _defaultProxyCache.Remember( weakReference, instance );

            var proxy = _proxyFactory.CreateProxy&lt;T&gt;( weakReference.Instance );
            return proxy;
        }

        protected virtual T GetInstance&lt;T&gt;()
        {
            return ServiceLocator.Current.GetInstance&lt;T&gt;();
        }
    }</pre>
</p>
<p>Now you can create a weak proxy simply by using the factory, or setting it up in an IoC container. To use the previous example of hooking IFoo to Foo, and injecting the weak reference into Baz objects, I can configure my application. This is going to look like a lot, but I am just being overly verbose showing how everything is set up.</p>
<pre>    public class WeakProxyProvider&lt;T&gt; : Provider&lt;T&gt;
    {
        #region Overrides of Provider&lt;T&gt;

        protected override T CreateInstance( IContext context )
        {
            return context.Kernel.Get&lt;WeakProxyFactory&gt;().GetProxy&lt;T&gt;();
        }

        #endregion
    }

        public static void Configure()
        {
            IKernel kernel = new StandardKernel();
            kernel.Bind( typeof (WeakProxyProvider&lt;&gt;) ).ToSelf().InSingletonScope();
            kernel.Bind&lt;IFoo&gt;().ToProvider&lt;WeakProxyProvider&lt;Foo&gt;&gt;().InTransientScope();
            kernel.Bind&lt;Foo&gt;().ToSelf().InTransientScope();
            kernel.Bind&lt;Baz&gt;().ToSelf().InTransientScope();
            kernel.Bind&lt;IWeakCache&gt;().To&lt;WeakProxyCache&gt;().InSingletonScope();
            kernel.Bind&lt;ICachePruner&gt;().To&lt;GarbageCollectionCachePruner&gt;()
                .WithConstructorArgument( &quot;pruneInterval&quot;, TimeSpan.FromSeconds( 1 ) );
            kernel.Bind&lt;WeakProxyCache&gt;().ToSelf();
            kernel.Bind&lt;WeakProxyFactory&gt;().ToSelf().InSingletonScope();

            var ninjectServiceLocator = new NinjectServiceLocator( kernel );
            ServiceLocator.SetLocatorProvider( () =&gt; ninjectServiceLocator );
        }</pre>
</p>
<p>So after all of this work, what does it buy me? My Baz objects now have IFoo weak proxy instances automatically injected into them when I make requests to the ServiceLocator. Once I null the pointer to the Foo object, the cache pruner will clean things up:</p>
<pre>    public static class SystemTest
    {
        private const int size = 6;

        public static void Run()
        {
            Configure();
            var bazs = new List&lt;Baz&gt;();
            for ( int i = 0; i &lt; size; i++ )
            {
                bazs.Add( ServiceLocator.Current.GetInstance&lt;Baz&gt;() ); // Where the magic happens
            }

            for ( int i = 0; i &lt; size; i++ )
            {
                Baz baz = bazs[i];
                Console.WriteLine( &quot;Foo Id: {0}&quot;, baz.Foo.Id );
                baz.Action();
                GC.Collect( 2 );

                baz.Release();
                GC.Collect( 2 ); // The Foo instances are disposed of by the system for you.
                Thread.Sleep( 100 );
            }
        }</pre>
</p>
<p>So, we have now seen a full implementation of a weak proxy factory handing out weak substitutes for the real objects. But what can we do from here? Is there anything else? YES! Now what we have full control over the real object lifetime, we can implement pooling. So, instead of handing out pointers to new weak objects, I can reuse objects in my pool, or use a lock to wait until a resource is available. These are both potentially big projects, so I am going to keep it small for now and just show a very minimalist example.</p>
<p>He is a small example that will let you set the size of the pool and it will reuse instances. Every time an instance is requested, we will clean the dead objects from the pool and refill if needed.</p>
<pre>    public class PoolingWeakProxyProvider&lt;T&gt; : Provider&lt;T&gt;
    {
        private int _currentIndex;
        private List&lt;Weak&lt;T&gt;&gt; _pool = new List&lt;Weak&lt;T&gt;&gt;();

        public PoolingWeakProxyProvider()
            : this( 5 )
        {
        }

        private PoolingWeakProxyProvider( int poolSize )
        {
            PoolSize = poolSize;
            _pool = new List&lt;Weak&lt;T&gt;&gt;();
        }

        #region Overrides of Provider&lt;T&gt;

        protected override T CreateInstance( IContext context )
        {
            lock ( _pool )
            {
                Prune();
                var proxyFactory = context.Kernel.Get&lt;WeakProxyFactory&gt;();
                if ( _pool.Count &lt; PoolSize )
                {
                    var item = proxyFactory.GetProxy&lt;T&gt;();
                    _pool.Add( new Weak&lt;T&gt;( item ) );
                    return item;
                }
                else
                {
                    return _pool[( _currentIndex++ ) % PoolSize].Instance;
                }
            }
        }

        #endregion

        public int PoolSize { get; private set; }

        public void Prune()
        {
            lock ( _pool )
            {
                var expired = _pool
                    .Where( item =&gt; !item.IsAlive )
                    .ToList();
                expired.ForEach( item =&gt; _pool.Remove( item ) );
            }
        }
    }</pre>
<p>Going back to our IoC container configuration (Ninject), we can put these two lines in:</p>
<pre>        public static void Configure()
        {
...
            kernel.Bind( typeof (PoolingWeakProxyProvider&lt;&gt;) ).ToSelf().InSingletonScope();
            kernel.Bind&lt;IFoo&gt;().ToProvider&lt;PoolingWeakProxyProvider&lt;Foo&gt;&gt;().InTransientScope();
...
        }</pre>
</p>
<p>I think that this can potentially be very useful in dealing with items such as WCF proxies. You could keep a pool and trim proxies as they age, and return them to requesters if there is no live usage, but the connection is still good.</p>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2009/08/weak-proxy-factory-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Weak Proxies</title>
		<link>http://innovatian.com/2009/07/weak-proxies-2/</link>
		<comments>http://innovatian.com/2009/07/weak-proxies-2/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 03:59:12 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://disassembla.net/blog/?p=106</guid>
		<description><![CDATA[I wanted my proxy factory to hand out instances, but clean up the instance as soon as the caller no longer needs the service. I also didn&#8217;t want the caller running the cleanup code. This allows me to pool proxy instances and clean them up as I see fit. There is an inherent issue with [...]]]></description>
			<content:encoded><![CDATA[<p></p><p style="text-align: left;">I wanted my proxy factory to hand out instances, but clean up the instance as soon as the caller no longer needs the service. I also didn&#8217;t want the caller running the cleanup code. This allows me to pool proxy instances and clean them up as I see fit.</p>
<p style="text-align: left;">There is an inherent issue with this idea: how do I know when the caller is done with the proxy? The answer, while not straight forward, is pretty cool. To start off, we will only consider what we hand off to the caller when the service is requested.</p>
<p style="text-align: left;">Let&#8217;s assume we have and IFoo contract and a Foo service that can be consumed. We want the caller to rely on the contract while we deal with the cleanup. Here is a very simple example.</p>
<pre>    public interface IFoo
    {
        void Bar();
    }

    public class Foo : IFoo, IDisposable
    {
        public bool IsDisposed { get; private set; }

        #region IDisposable Members

        public void Dispose()
        {
            IsDisposed = true;
        }

        #endregion

        #region IFoo Members

        public void Bar()
        {
            Console.WriteLine( &amp;quot;Foo::Bar&amp;quot; );
        }

        #endregion
    }</pre>
<p style="text-align: left;">Now we want to hand out IFoo, and allow the caller to release control of the service. This is done most simply in two ways. First, use the pointer to the IFoo service and then go out of scope. Second, hold the IFoo pointer in a member variable and set it to null when done. For the sake of the example, we are going to play with the second option.</p>
<pre>    public class Baz
    {
        private IFoo _foo;

        public Baz( IFoo foo )
        {
            _foo = foo;
        }

        public void Action()
        {
            _foo.Bar();
        }

        public void Release()
        {
            _foo = null;
        }
    }</pre>
<p style="text-align: left;">We can supply the IFoo into the Baz instance via dependency injection. When we are done with the IFoo instance, we set the pointer to null, or the GC will do it for us when the object goes out of scope. This gives us a very simple model from which things get a lot more fun.</p>
<p style="text-align: left;">Weak&lt;T&gt; is the base for this post. It is a WeakReference with strongly typed access to the target instance. This can be optimized, but is much more understandable as-is.</p>
<pre>    public class Weak&lt;T&gt; : WeakReference
    {
        public Weak( T target )
            : base( target )
        {
        }

        protected Weak( T target, bool trackResurrection )
            : base( target, trackResurrection )
        {
        }

        protected Weak( SerializationInfo info, StreamingContext context )
            : base( info, context )
        {
        }

        public T Instance
        {
            get { return (T) Target; }
        }
    }</pre>
<p style="text-align: left;">We can extend this class to create a decorator proxy based on the weak reference to the real service:</p>
<pre>    public class WeekFoo : Weak&lt;IFoo&gt;, IFoo
    {
        public WeekFoo( IFoo target )
            : base( target )
        {
        }

        protected WeekFoo( IFoo target, bool trackResurrection )
            : base( target, trackResurrection )
        {
        }

        protected WeekFoo( SerializationInfo info, StreamingContext context )
            : base( info, context )
        {
        }

        #region IFoo Members

        void IFoo.Bar()
        {
            Instance.Bar();
        }

        #endregion
    }</pre>
<p style="text-align: left;">Now we have an object with a weak reference base that behaves like an IFoo. There is a drawback to this which should be pretty obvious: you have to generate a proxy for every service you want to track and hand-write every method in the interface. This is where a dynamic proxy framework like Castle.DynamicProxy2 or LinFu.DynamicProxy can save us a lot of time. For the example, I am going to use LinFu. Really, all we want is a wrapper that will use the underlying weak object to make the interface calls for us. We can also set it up to throw if we have released the weak reference.</p>
<pre>    public class WeakInterceptor&lt;T&gt; : IInvokeWrapper
    {
        private readonly Weak&lt;T&gt; _target;

        public WeakInterceptor( Weak&lt;T&gt; target )
        {
            _target = target;
        }

        #region IInvokeWrapper Members

        public void BeforeInvoke( InvocationInfo info )
        {
        }

        public object DoInvoke( InvocationInfo info )
        {
            T instance = _target.Instance;
            if ( _target.IsAlive )
            {
                return info.TargetMethod.Invoke( instance, info.Arguments );
            }
            throw new InvalidOperationException();
        }

        public void AfterInvoke( InvocationInfo info, object returnValue )
        {
        }

        #endregion
    }</pre>
<p style="text-align: left;">This is a much more elegant approach and requires very little work to set up a full interface proxy around the weak reference for each service we want to wrap. Finally, we can test the code out to make sure our assumptions are working correctly.</p>
<pre>    internal class Program
    {
        private static void Main( string[] args )
        {
            LinFu();
            ManualProxy();
            Console.ReadLine();
        }

        public static void LinFu()
        {
            var foo = new Foo();
            var weakReference = new Weak&lt;WeakInterceptor&lt;IFoo&gt;&gt;(
                new WeakInterceptor&lt;IFoo&gt;;(
                    new Weak&lt;IFoo&gt;( foo ) ) );
            var proxyFactory = new ProxyFactory();
            var baz = new Baz( proxyFactory.CreateProxy&lt;IFoo&gt;( weakReference.Instance ) );

            Verify( foo, weakReference, baz );
        }

        private static void ManualProxy()
        {
            var foo = new Foo();
            var weakReference = new Weak&lt;WeekFoo&gt;( new WeekFoo( foo ) );
            var baz = new Baz( weakReference.Target as IFoo );

            Verify( foo, weakReference, baz );
        }

        private static void Verify( Foo foo, WeakReference weakReference, Baz baz )
        {
            baz.Action();
            GC.Collect();

            Debug.Assert( weakReference.IsAlive );
            baz.Release();
            GC.Collect();

            Debug.Assert( weakReference.IsAlive == false );
            foo.Dispose();
            Debug.Assert( foo.IsDisposed );
        }
    }</pre>
<p style="text-align: left;">We now have two methods for handing out weak service references to clients and allowing us to control the lifetime of the services for pooling, disposal, or whatever else we want to do without the client having to deal with the details. This is just a basic example. You can easily extend this into a service factory/container and track the instances you hand out.</p>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2009/07/weak-proxies-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

