<?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>The Inquisitive Coder - Davy Brion&#039;s Blog &#187; Castle Windsor</title> <atom:link href="http://davybrion.com/blog/category/castle-windsor/feed/" rel="self" type="application/rss+xml" /><link>http://davybrion.com/blog</link> <description>inquisitive: adjective. given to inquiry, research, or asking questions; eager for knowledge; intellectually curious</description> <lastBuildDate>Mon, 14 May 2012 21:08:36 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.2</generator> <item><title>Avoiding Memory Leaks With NServiceBus And Your Own Castle Windsor Instance</title><link>http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/</link> <comments>http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/#comments</comments> <pubDate>Fri, 19 Feb 2010 09:42:55 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Memory Management]]></category> <category><![CDATA[nservicebus]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2268</guid> <description><![CDATA[If you’re using NServiceBus together with your own instance of Castle Windsor, there is one thing you really need to look out for.&#160; NServiceBus was originally developed with Spring.NET as its IoC container, but it’s been changed to support multiple containers in a similar manner as Agatha does it.&#160; Agatha however, was originally developed with [...]]]></description> <content:encoded><![CDATA[<p>If you’re using NServiceBus together with your own instance of Castle Windsor, there is one thing you really need to look out for.&#160; NServiceBus was originally developed with Spring.NET as its IoC container, but it’s been changed to support multiple containers in a similar manner as <a
href="http://davybrion.com/blog/2009/11/integrating-your-ioc-container-with-agatha/" target="_blank">Agatha does it</a>.&#160; Agatha however, was originally developed with Castle Windsor as its IoC container, and as such is well aware of Windsor’s <a
href="http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/" target="_blank">need to explicitly release resolved components</a>.&#160;&#160; NServiceBus unfortunately was <a
href="http://tech.groups.yahoo.com/group/nservicebus/message/5376" target="_blank">not aware of this need</a>, and a workaround that they have introduced is to set Windsor’s ReleasePolicy to the NoTrackingReleasePolicy (which doesn’t hold any instances in memory, but doesn’t provide any cleanup either) if you configure NServiceBus to use <em>its own instance of </em>Castle Windsor.&#160; However, if you’re integrating NServiceBus into a project that is already using Castle Windsor, then you probably want NServiceBus to use <em>your instance</em> of Castle Windsor.</p><p>And that is when problems might appear.&#160; If you’re using Castle Windsor with the default ReleasePolicy (which is the LifecycledComponentsReleasePolicy) then each resolved transient instance will be stored in memory by that policy until the instance is explicitly released.&#160; The benefit of this policy is that the container can automatically dispose any disposable transient dependency of a resolved component.&#160; In my case, i’ve come to rely on that feature to achieve deterministic disposal behavior throughout my code base.&#160;</p><p>Now, when you configure NServiceBus and pass it your instance of Castle Windsor, it obviously doesn’t change the ReleasePolicy like it does when it creates its own instance of Castle Windsor.&#160;&#160; This is good because changing the policy of a passed in container would almost certainly have a huge behavioral implication for the application and such an action would be unacceptable when integrating a new framework into your project.&#160;&#160; But since NServiceBus doesn’t have the notion of needing to release resolved components, every single transient instance it resolves through <em>your</em> container will be stored in memory until the application’s process is terminated.&#160; Which means that you’ll leak instances of the following types <em>for each message</em> that your system needs to handle:</p><ul><li>NServiceBus.Grid.MessageHandlers.GridInterceptingMessageHandler</li><li>NServiceBus.Sagas.Impl.SagaMessageHandler</li><li>Your own MessageHandlers (and their transient dependencies as well)</li></ul><p>If your MessageHandlers don’t have dependencies (highly unlikely if you’re already using an IOC container) then you’d still have 3 leaking instances per incoming message.&#160; Add the number of transient dependencies of any handler to that and the number of leaking instances can increase dramatically.</p><p>First of all, if you do not depend on Windsor’s default ReleasePolicy’s behavior, then the easiest way to avoid this problem is definitely to set the container’s ReleasePolicy to the NoTrackingReleasePolicy like NServiceBus does itself when it’s configuring itself with a new instance of the container.</p><p>If you do depend on it, and you don’t want leaking instances that hang around forever, then the approach listed below is one way to solve this problem.&#160; There are probably other solutions available, and while the approach listed below can definitely be considered to be a HACK, i do think it’s the best solution to this particular problem.</p><p>Because we don’t want to change anything about the way that we’re already using the container, we just need to make sure that NServiceBus’ usage of the container doesn’t conflict with ours.&#160; That basically means that we need to make sure that the components that it resolves should not be tracked by the container.&#160;&#160; There are 2 kinds of components that NServiceBus will resolve during normal operation:</p><ol><li>Its own components that it needs to implement the features it offers you</li><li>Your message handlers that you need to handle incoming messages</li></ol><p>The first category is easy to exclude from Windsor’s tracking behavior.&#160; We can simply create our own ReleasePolicy which extends the default ReleasePolicy, and make sure that any instances of an NServiceBus-type are no longer tracked by the container:</p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">class</span> <span
style="color: #2b91af">MyReleasePolicy</span> : Castle.MicroKernel.Releasers.<span
style="color: #2b91af">LifecycledComponentsReleasePolicy</span></p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">override</span> <span
style="color: blue">void</span> Track(<span
style="color: blue">object</span> instance, Castle.MicroKernel.<span
style="color: #2b91af">Burden</span> burden)</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">if</span> (!instance.GetType().FullName.StartsWith(<span
style="color: #a31515">&quot;NServiceBus&quot;</span>))</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">base</span>.Track(instance, burden);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p></div><p>&#160;</p><p>Then you need to set this release policy somewhere in your application’s startup routine:</p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">IoC</span>.Container.Kernel.ReleasePolicy = <span
style="color: blue">new</span> <span
style="color: #2b91af">MyReleasePolicy</span>();</p></div><p>&#160;</p><p>(in this case, IoC.Container returns an IWindsorContainer instance)</p><p>This will make sure that no instances of NServiceBus-types will ever leak in the container.&#160; But now we still have to deal with our message handlers.&#160; The solution to making sure they are not disposed is not the cleanest out there but hey, it works.&#160; I basically introduced a base class that all my message handlers will need to inherit from, with the following implementation in the Handle method:</p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">abstract</span> <span
style="color: blue">class</span> <span
style="color: #2b91af">MessageHandler</span>&lt;TMessage&gt; : <span
style="color: #2b91af">IMessageHandler</span>&lt;TMessage&gt; <span
style="color: blue">where</span> TMessage : <span
style="color: #2b91af">IMessage</span></p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> Handle(TMessage message)</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">try</span></p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Process(message);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">finally</span></p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: green">// ugly as hell, but we need this until NSB releases its resolved components</span></p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">IoC</span>.Container.Release(<span
style="color: blue">this</span>);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">protected</span> <span
style="color: blue">abstract</span> <span
style="color: blue">void</span> Process(TMessage message);</p><p
style="margin: 0px">&#160;&#160;&#160; }</p></div><p>&#160;</p><p>Uh oh… i just felt a great disturbance in the Force, as if tens of voices suddenly cried out in terror about my direct usage of the IoC container in a component!</p><p>Conceptually, this is wrong on many levels.&#160; Then again, this makes sure that the message handlers (and their dependencies) that are resolved by NServiceBus will always be guaranteed to be released by the comtainer.&#160; It might not be nice, but it avoids the memory leak and it doesn’t force me to change <em>my other code</em>.</p><p>And once NServiceBus is modified to release the components it resolves (if it’s ever modified that is…) i only need to get rid of my custom policy and the try/finally block.&#160; Unfortunately, my existing message handlers will then all implement the Process method instead of the Handle method but that is quickly fixed with a simple rename-refactoring.</p><p>Even though this is a pretty big hack (IMHO), at least its impact on the code is minimal… it will be easy to get rid of once the real problem is solved in NSB, and there are no real downsides to this that i can think of at the moment.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2010%2F02%2Favoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/"  data-text="Avoiding Memory Leaks With NServiceBus And Your Own Castle Windsor Instance" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/feed/</wfw:commentRss> <slash:comments>15</slash:comments> </item> <item><title>Protecting Your Application From Remote Problems</title><link>http://davybrion.com/blog/2009/07/protecting-your-application-from-remote-problems/</link> <comments>http://davybrion.com/blog/2009/07/protecting-your-application-from-remote-problems/#comments</comments> <pubDate>Sun, 05 Jul 2009 19:45:41 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Aspect Oriented Programming]]></category> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Patterns]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=1443</guid> <description><![CDATA[If you have a web application which communicates with a remote service, it's important to protect that web application from any problems the remote service might be dealing with. For instance, if the remote service goes down (for whatever reason) you really don't want your application to keep making calls to this service. These failing [...]]]></description> <content:encoded><![CDATA[<p>If you have a web application which communicates with a remote service, it's important to protect that web application from any problems the remote service might be dealing with.  For instance, if the remote service goes down (for whatever reason) you really don't want your application to keep making calls to this service.  These failing calls increase the load on the service, which is already having problems, and will also block your threads which takes away resources from your application to deal with other requests.  One pattern which is very suitable to reduce the problems for this situation is the <a
href="http://davybrion.com/blog/2008/05/the-circuit-breaker/">Circuit Breaker</a> (read that unless you're familiar with the circuit breaker).</p><p>The biggest issue i have with my previous implementation is that it required you to call it manually to protect potentially risky calls.  I don't like having to call my circuit breaker whenever i want to make a service call because as a consumer of a service proxy, i shouldn't even know about the circuit breaker.  I also don't want any coupling between my service proxy and the actual circuit breaker.  Sounds like a good candidate for some AOP magic, right?</p><p>We're going to use Castle Windsor's Interceptors to make this work.  First, the implementation of the CircuitBreaker class:</p><div><pre class="brush: csharp; title: ; notranslate">
    public class CircuitBreaker : IInterceptor
    {
        private readonly object monitor = new object();
        private CircuitBreakerState state;
        private int failures;
        private int threshold;
        private TimeSpan timeout;
 
        public CircuitBreaker(int threshold, TimeSpan timeout)
        {
            this.threshold = threshold;
            this.timeout = timeout;
            MoveToClosedState();
        }
 
        public void Intercept(IInvocation invocation)
        {
            using (TimedLock.Lock(monitor))
            {
                state.ProtectedCodeIsAboutToBeCalled();
            }
 
            try
            {
                invocation.Proceed();
            }
            catch (Exception e)
            {
                using (TimedLock.Lock(monitor))
                {
                    failures++;
                    state.ActUponException(e);
                }
                throw;
            }
 
            using (TimedLock.Lock(monitor))
            {
                state.ProtectedCodeHasBeenCalled();
            }
        }
 
        private void MoveToClosedState()
        {
            state = new ClosedState(this);
        }
 
        private void MoveToOpenState()
        {
            state = new OpenState(this);
        }
 
        private void MoveToHalfOpenState()
        {
            state = new HalfOpenState(this);
        }
 
        private void ResetFailureCount()
        {
            failures = 0;
        }
 
        private bool ThresholdReached()
        {
            return failures &gt;= threshold;
        }
 
        private abstract class CircuitBreakerState
        {
            protected readonly CircuitBreaker circuitBreaker;
 
            protected CircuitBreakerState(CircuitBreaker circuitBreaker)
            {
                this.circuitBreaker = circuitBreaker;
            }
 
            public virtual void ProtectedCodeIsAboutToBeCalled() { }
            public virtual void ProtectedCodeHasBeenCalled() { }
            public virtual void ActUponException(Exception e) { }
        }
 
        private class ClosedState : CircuitBreakerState
        {
            public ClosedState(CircuitBreaker circuitBreaker)
                : base(circuitBreaker)
            {
                circuitBreaker.ResetFailureCount();
            }
 
            public override void ActUponException(Exception e)
            {
                if (circuitBreaker.ThresholdReached()) circuitBreaker.MoveToOpenState();
            }
        }
 
        private class OpenState : CircuitBreakerState
        {
            private readonly Timer timer;
 
            public OpenState(CircuitBreaker circuitBreaker)
                : base(circuitBreaker)
            {
                timer = new Timer(circuitBreaker.timeout.TotalMilliseconds);
                timer.Elapsed += TimeoutHasBeenReached;
                timer.AutoReset = false;
                timer.Start();
            }
 
            private void TimeoutHasBeenReached(object sender, ElapsedEventArgs e)
            {
                circuitBreaker.MoveToHalfOpenState();
            }
 
            public override void ProtectedCodeIsAboutToBeCalled()
            {
                throw new OpenCircuitException();
            }
        }
 
        private class HalfOpenState : CircuitBreakerState
        {
            public HalfOpenState(CircuitBreaker circuitBreaker) : base(circuitBreaker) { }
 
            public override void ActUponException(Exception e)
            {
                circuitBreaker.MoveToOpenState();
            }
 
            public override void ProtectedCodeHasBeenCalled()
            {
                circuitBreaker.MoveToClosedState();
            }
        }
    }
</pre></div><p>Notice how the CircuitBreaker class implements Windsor's IInterceptor interface.  The Intercept method will be called by Windsor whenever we try to call a method from a protected component.  Within the Intercept method we can add the necessary logic to apply the Circuit Breaker pattern to the code that was originally called.</p><p>Now we just need to configure the Windsor IOC container to apply this bit of AOP magic for us.</p><p>First, we register the CircuitBreaker with the container:</p><div><pre class="brush: csharp; title: ; notranslate">
            container.Register(Component.For&lt;CircuitBreaker&gt;().LifeStyle.Singleton
                                   .Named(&quot;serviceProxyCircuitBreaker&quot;)
                                   .DependsOn(new Hashtable { { &quot;threshold&quot;, 5 }, { &quot;timeout&quot;, TimeSpan.FromMinutes(5) } }));
</pre></div><p>Notice that we register the CircuitBreaker implementation with a Singleton lifestyle, a custom name and the required constructor parameters to create an instance of the CircuitBreaker.</p><p>Then we register our service proxy:</p><div><pre class="brush: csharp; title: ; notranslate">
            container.Register(Component.For&lt;IServiceProxy&gt;().ImplementedBy&lt;ServiceProxy&gt;().LifeStyle.Transient
                                .Interceptors(InterceptorReference.ForKey(&quot;serviceProxyCircuitBreaker&quot;)).Anywhere);
</pre></div><p>Notice how we registered the service proxy as a transient component, while referencing the singleton CircuitBreaker interceptor.  This means that each resolved instance of our service proxy will be protected by the same CircuitBreaker instance.  If you have multiple services that you want to protect, simply register multiple CircuitBreakers with different keys and link each service you want to protect with the correct CircuitBreaker key.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2009%2F07%2Fprotecting-your-application-from-remote-problems%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2009/07/protecting-your-application-from-remote-problems/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2009/07/protecting-your-application-from-remote-problems/"  data-text="Protecting Your Application From Remote Problems" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2009/07/protecting-your-application-from-remote-problems/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2009/07/protecting-your-application-from-remote-problems/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2009/07/protecting-your-application-from-remote-problems/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>The Resolvable</title><link>http://davybrion.com/blog/2008/12/the-resolvable/</link> <comments>http://davybrion.com/blog/2008/12/the-resolvable/#comments</comments> <pubDate>Sun, 21 Dec 2008 14:48:26 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Memory Management]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=737</guid> <description><![CDATA[I wrote a post last week about a memory leak i had introduced in my code due to not properly releasing resolved components through the Windsor IoC container. I wanted to try to make sure that i'd never make that mistake again and this is the approach i came up with. If you're using an [...]]]></description> <content:encoded><![CDATA[<p>I wrote a post last week about a memory leak i had introduced in my code due to <a
href="http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/">not properly releasing resolved components through the Windsor IoC container</a>.  I wanted to try to make sure that i'd never make that mistake again and this is the approach i came up with.</p><p>If you're using an IOC container it's important to not use it all over the place.  You basically use it in as few places as possible to resolve a component and you let the container sort out all of the dependencies.  So in the few places where you use the container directly, you need to resolve the component, and in case of transient components you also need to release them through the container.  Releasing it is very easy to forget, so i wanted something that would guarantee that the component would be properly released.  Enter the Resolvable class:</p><div><pre class="brush: csharp; title: ; notranslate">
    public class Resolvable&lt;T&gt; : Disposable
    {
        private readonly T instance;
 
        public Resolvable() : this(null) {}
 
        public Resolvable(object argumentsAsAnonymousType)
        {
            if (argumentsAsAnonymousType == null)
            {
                instance = IoC.Container.Resolve&lt;T&gt;();
            }
            else
            {
                instance = IoC.Container.Resolve&lt;T&gt;(argumentsAsAnonymousType);
            }
        }
 
        public T Instance
        {
            get { return instance; }
        }
 
        protected override void DisposeManagedResources()
        {
            IoC.Container.Release(instance);
        }
    }
</pre></div><p>The Resolvable class inherits from my <a
href="http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/">Disposable class</a>, so the Disposable pattern is correctly implemented.</p><p>From now on, instead of calling the container directly, i just instantiate a new Resolvable in a using block.  Let's try it out.</p><p>I'm reusing my test component with a dependency from one of the previous posts:</p><div><pre class="brush: csharp; title: ; notranslate">
    public interface IDependency : IDisposable
    {
        bool Disposed { get; set; }
    }
 
    public class MyDependency : IDependency
    {
        public bool Disposed { get; set; }
 
        public void Dispose()
        {
            Disposed = true;
        }
    }
 
    public interface IController : IDisposable
    {
        bool Disposed { get; set; }
        IDependency Dependency { get; }
    }
 
    public class Controller : IController
    {
        public IDependency Dependency { get; private set; }
 
        public Controller(IDependency myDependency)
        {
            Dependency = myDependency;
        }
 
        public void Dispose()
        {
            Dependency.Dispose();
            Disposed = true;
        }
 
        public bool Disposed { get; set; }
    }
</pre></div><p>Now, instead of resolving an IController directly through the container and having to dispose of it, i just do this:</p><div><pre class="brush: csharp; title: ; notranslate">
        [Test]
        public void ResolvableInstanceIsProperlyReleasedAfterDisposal()
        {
            IoC.Container.Register(Component.For&lt;IController&gt;().ImplementedBy&lt;Controller&gt;().LifeStyle.Transient);
            IoC.Container.Register(Component.For&lt;IDependency&gt;().ImplementedBy&lt;MyDependency&gt;().LifeStyle.Transient);
 
            IController controller;
            IDependency dependency;
 
            using (var resolvable = new Resolvable&lt;IController&gt;())
            {
                controller = resolvable.Instance;
                dependency = controller.Dependency;
            }
 
            Assert.IsTrue(controller.Disposed);
            Assert.IsTrue(dependency.Disposed);
            Assert.IsFalse(IoC.Container.Kernel.ReleasePolicy.HasTrack(controller));
            Assert.IsFalse(IoC.Container.Kernel.ReleasePolicy.HasTrack(dependency));
        }
</pre></div><p>The container doesn't hold the reference to the instance, and both the instance and its dependency is properly disposed.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F12%2Fthe-resolvable%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/12/the-resolvable/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/12/the-resolvable/"  data-text="The Resolvable" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/12/the-resolvable/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/12/the-resolvable/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/12/the-resolvable/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>The Component Burden</title><link>http://davybrion.com/blog/2008/12/the-component-burden/</link> <comments>http://davybrion.com/blog/2008/12/the-component-burden/#comments</comments> <pubDate>Sun, 14 Dec 2008 12:37:23 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Memory Management]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=722</guid> <description><![CDATA[In my previous post i showed you how important it is to properly release the components you've resolved through the Windsor IoC container. At the end of that post, i showed an example where a disposable dependency of a component had to be disposed by the component. Basically something like this: This prompted the following [...]]]></description> <content:encoded><![CDATA[<p>In my <a
href="http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/">previous post</a> i showed you how important it is to properly release the components you've resolved through the Windsor IoC container.  At the end of that post, i showed an example where a disposable dependency of a component had to be disposed by the component.  Basically something like this:</p><div><pre class="brush: csharp; title: ; notranslate">
    public class Controller : IController
    {
        public IDependency Dependency { get; private set; }
 
        public Controller(IDependency myDependency)
        {
            Dependency = myDependency;
        }
 
        public void Dispose()
        {
            Dependency.Dispose();
        }
    }
</pre></div><p>This prompted the following <a
href="http://elegantcode.com/2008/12/13/the-importance-of-releasing-your-components-through-windsor/#comment-39632">comment</a> by Bryan Watts:</p><blockquote> So Controller is responsible for disposing of something it did not explicitly create? That’s a little presumptuous isn’t it?<blockquote> > if you own a reference to an IDisposable instance, you are responsible for properly disposing of that instance.</blockquote>I agree (and I’ve read your other article). However, in this case, Controller clearly does not own its dependency.</blockquote><p>And Bryan is right.  For a lot of languages, memory management rules can be summarized (somewhat simplified) like this:</p><ul><li>If you create an instance of a class, you are responsible for releasing/freeing/disposing it.</li><li>If a factory creates an instance of a class, the factory is not responsible for releasing/freeing/disposing it.  This burden falls upon the object which requested the object from the factory</li><li>If you receive an instance of an object, you should not release/free/dispose it, unless you received the instance from a factory</li></ul><p>So where does this leave us with the example code shown above?  Clearly, we did not create the instance of the disposable dependency, so in theory, we are not allowed to dispose it.  Then again, if we weren't using Dependency Injection we would have probably instantiated the disposable dependency in our constructor (or when we first need it).  In that case, we would have been responsible for disposing the disposable dependency.</p><p>You could argue that the IoC container is in some way a factory which creates and supplies the dependency to our class.  So according to the rules stated above, it would be allowed to dispose the dependency.   The downside to this is that this means that our class (the Controller) has knowledge of the lifecycle of the dependency.  We know that the dependency has been configured with a Transient lifecycle (which means the container creates a new instance whenever an instance of its class is needed) so we can safely dispose it.  The problem is that this knowledge is implicit.  It is nowhere visible in the code of the Controller class.  The only place where this lifecycle is configured explicitly, is in the configuration of the IoC container so it would be wrong for the Controller to assume anything about the lifecycle of its dependencies.</p><p>After all, suppose someone makes a change to the code of the dependency which makes it possible to be used with a different lifecycle.  Suppose someone makes the change to the dependency and then configures the IoC container to always return a singleton instance of this dependency.  If nobody thinks about the fact that the Controller still assumes a Transient lifecycle of the dependency, the disposal of the dependency will not be removed from the Controller class.  Once a Controller instance is created, and then disposed, it will try to dispose the instance of its dependency, which will cause problems because that instance is supposed to be used by other objects as well!</p><p>So what do we do? Do we dispose of the dependency in the Controller class because we know it's safe (until someone changes the dependency and/or its configuration with the container)?  Or do we simply not dispose it (since we're not really allowed to do so without some kind of implicit knowledge of the 'outside world')?</p><p>Neither option sounds very appealing.  The first option <strong>could</strong> lead to problems depending on possible future changes outside of the Controller class.  The second option <strong>is already problematic</strong> because a disposable dependency is not being disposed of as fast as it should be.  The disposal would basically be postponed until the instance is collected by the garbage collector.</p><p>Another alternative is to have the container inject a factory which can create transient instances of the dependency, instead of having the container inject the transient instance directly.  This would fix all of the discussed problems: the controller would not need to dispose the injected dependency, and can safely dispose the instantiated disposable instances.  However, having to create factories simply to avoid this problem seems a bit cumbersome.  The implementation of the factory could lead to other discussions as well because of how the factory should create the actual instance <strong>and its dependencies</strong>, which is exactly the reason why we wanted to use an IoC container in the first place.  True, the factory could resolve the instance directly through the IoC container, but then you're just moving the problem to a different class without actually fixing it properly.</p><p>This entire problem has been described as the <a
href="http://hammett.castleproject.org/?p=252">Component Burden</a> by Hammet, the original creator of the Windsor IoC container.  Obviously, this is something that the container should solve for us instead of us having to worry about it.  Ideally, the container would keep track of all of the disposable dependencies it has created to satisfy the creation of requested components.  Then when the requested component would be released, the container could safely dispose of each transient disposable dependency it created to create the requested component.  Luckily, the Castle developers have implemented this behavior <a
href="http://www.nabble.com/Component-burden-impl-committed-td19848831.html">recently</a>, so if you're using a recent build of the Windsor IoC container,  this problem should no longer occur and you shouldn't be forced to dispose of dependencies that were injected into your objects.</p><p>The reason why i'm not using it yet is because there were many attempts at implementing this, and most attempts had considerable downsides to them.  This one has been committed to the trunk, so it's probably a good solution, but i'm not going to use this solution in production systems until it has had some more time to prove itself.  So for now, i'm sticking with my approach where i manually dispose the injected dependencies.  I know it's not the best approach, but until the real solution in the container is somewhat more proven to work without downsides, manually disposing the dependencies seems to be the lesser of multiple evils.</p><p>Keep in mind that i'm only talking about the Windsor IoC container.  I have no experience with StructureMap, NInject or Unity, so i have no idea how these containers deal with this problems.  If anyone with knowledge about these container could shed some light on how they deal with this, i'd be very interested in reading it <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F12%2Fthe-component-burden%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/12/the-component-burden/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/12/the-component-burden/"  data-text="The Component Burden" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/12/the-component-burden/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/12/the-component-burden/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/12/the-component-burden/feed/</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>The Importance Of Releasing Your Components Through Windsor</title><link>http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/</link> <comments>http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/#comments</comments> <pubDate>Sat, 13 Dec 2008 14:12:45 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Memory Management]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=718</guid> <description><![CDATA[We ran into a huge memory leak this week. A bit of memory profiling with JetBrains' dotTrace quickly showed that the Windsor IoC container was holding on to a lot of references. It turned out that i actually forgot to release the components i was requesting Windsor to construct for me. I use the container [...]]]></description> <content:encoded><![CDATA[<p>We ran into a huge memory leak this week. A bit of memory profiling with JetBrains' <a
href="http://www.jetbrains.com/profiler/index.html">dotTrace</a> quickly showed that the Windsor IoC container was holding on to a lot of references. It turned out that i actually forgot to release the components i was requesting Windsor to construct for me. I use the container in my web-layer to compose every page's Controller with its dependencies. And in my service layer, i use the container to compose every RequestHandler and its dependencies. So that's two instances of the Container, in two separate AppDomains, and both are leaking a lot of memory due to my mistake.</p><p>My mistake was that after i was done with the components that i asked Windsor to resolve, i simply disposed them (which in turn would dispose their dependencies) and i figured that would be enough, since my components are registered as Transient. That means that each time you request a Transient component, you get a new instance. This led me to believe that Windsor wouldn't need to hold a reference to the constructed components so i figured that simply disposing them would be enough, since they are IDisposables. Disposing them is a good thing obviously, but because the container was still holding references to the requested components, that's still a lot of memory that is being wasted because even though you've disposed them, they aren't eligible for Garbage Collection until they are no longer accessible. And because the container kept references to them, they remained accessible and were never collected. And there was my memory leak. Oops.</p><p>In order to prevent this problem in the future for myself and anyone else who reads this, let's go over a few examples which should make it clear how you should make sure that your components are properly released so they are eligible for garbage collection.</p><p>Let's start really simple. We have an IController interface and a simple Controller class which implements the IController interface:</p><p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">interface</span> <span
style="color: #2b91af">IController</span> : <span
style="color: #2b91af">IDisposable</span></p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">bool</span> Disposed { <span
style="color: blue">get</span>; <span
style="color: blue">set</span>; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">class</span> <span
style="color: #2b91af">Controller</span> : <span
style="color: #2b91af">IController</span></p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> Dispose()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Disposed = <span
style="color: blue">true</span>;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">bool</span> Disposed { <span
style="color: blue">get</span>; <span
style="color: blue">set</span>; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p></div><p></p></p><p>In our tests, we'll use the following method to create and configure the container:</p><p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">private</span> <span
style="color: #2b91af">WindsorContainer</span> CreateContainer()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> container = <span
style="color: blue">new</span> <span
style="color: #2b91af">WindsorContainer</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; container.Register(<span
style="color: #2b91af">Component</span>.For&lt;<span
style="color: #2b91af">IController</span>&gt;().ImplementedBy&lt;<span
style="color: #2b91af">Controller</span>&gt;().LifeStyle.Transient);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">return</span> container;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p></div><p></p></p><p>The IController interface is registered with the container, and the container will return a new Controller instance (because of the Transient lifestyle) whenever someone requests an IController instance.</p><p>The following test highlights the memory leak that i was experiencing:</p><p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span
style="color: #2b91af">Test</span>]</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> ContainerKeepsReferenceToControllerIfWeOnlyDisposeOfIt()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> container = CreateContainer();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> controller = container.Resolve&lt;<span
style="color: #2b91af">IController</span>&gt;();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.That(container.Kernel.ReleasePolicy.HasTrack(controller));</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; controller.Dispose();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.IsTrue(controller.Disposed);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: green">// the controller is disposed of, but the container is still keeping track</span></p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: green">// of the instance</span></p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.That(container.Kernel.ReleasePolicy.HasTrack(controller));</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p></div><p></p></p><p>When you request a component from the Container, it keeps a reference to that instance in its Kernel's ReleasePolicy object. If you merely dispose of your requested component, the ReleasePolicy still holds the reference to the component. This is what caused my memory leak.</p><p>So how do we avoid this problem? It's pretty easy actually:</p><p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span
style="color: #2b91af">Test</span>]</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> ContainerDoesNotKeepReferenceToControllerIfWeReleaseIt()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> container = CreateContainer();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> controller = container.Resolve&lt;<span
style="color: #2b91af">IController</span>&gt;();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.That(container.Kernel.ReleasePolicy.HasTrack(controller));</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: green">// instead of disposing the controller, we'll Release it through the container</span></p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; container.Release(controller);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.IsTrue(controller.Disposed);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: green">// the controller is disposed of, and the container is no longer keeping</span></p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: green">// track of the instance</span></p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.IsFalse(container.Kernel.ReleasePolicy.HasTrack(controller));</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p></div><p></p></p><p>Instead of just disposing our controller, we tell the container to release it. The container in turn knows that because IController inherits from IDisposable, it should dispose the Controller instance. It also removes the instance from its Kernel's ReleasePolicy object and once your own reference to the Controller instance goes out of scope, it's eligible to be collected by the Garbage Collector.</p><p>As you can see, it's very easy to make sure your components are properly released and eligible for garbage collection. But what about possible dependencies of your components? Let's take a look.</p><p>Suppose we define the following interface and implementation:</p><p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">interface</span> <span
style="color: #2b91af">IDependency</span> { }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">class</span> <span
style="color: #2b91af">MyDependency</span> : <span
style="color: #2b91af">IDependency</span> { }</p></div><p></p></p><p>The dependency doesn't actually do anything, but bear with me <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><p>We modify the IController interface and Controller implementation like this:</p><p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">interface</span> <span
style="color: #2b91af">IController</span> : <span
style="color: #2b91af">IDisposable</span></p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">bool</span> Disposed { <span
style="color: blue">get</span>; <span
style="color: blue">set</span>; }</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">IDependency</span> Dependency { <span
style="color: blue">get</span>; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">class</span> <span
style="color: #2b91af">Controller</span> : <span
style="color: #2b91af">IController</span></p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: #2b91af">IDependency</span> Dependency { <span
style="color: blue">get</span>; <span
style="color: blue">private</span> <span
style="color: blue">set</span>; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> Controller(<span
style="color: #2b91af">IDependency</span> myDependency)</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Dependency = myDependency;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> Dispose()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Disposed = <span
style="color: blue">true</span>;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">bool</span> Disposed { <span
style="color: blue">get</span>; <span
style="color: blue">set</span>; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p></div><p></p></p><p>And then we modify the configuration of the container like this:</p><p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">private</span> <span
style="color: #2b91af">WindsorContainer</span> CreateContainer()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> container = <span
style="color: blue">new</span> <span
style="color: #2b91af">WindsorContainer</span>();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; container.Register(<span
style="color: #2b91af">Component</span>.For&lt;<span
style="color: #2b91af">IController</span>&gt;().ImplementedBy&lt;<span
style="color: #2b91af">Controller</span>&gt;().LifeStyle.Transient);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; container.Register(<span
style="color: #2b91af">Component</span>.For&lt;<span
style="color: #2b91af">IDependency</span>&gt;().ImplementedBy&lt;<span
style="color: #2b91af">MyDependency</span>&gt;().LifeStyle.Transient);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">return</span> container;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p></div><p></p></p><p>Whenever we request an IController instance, the container will construct a Controller instance and will pass a MyDependency instance to the Controller's instance constructor. The question now is: does the container also track the instances of a requested component's dependencies? The answer is: no</p><p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span
style="color: #2b91af">Test</span>]</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> ContainerDoesNotKeepReferenceToControllersDependencies()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> container = CreateContainer();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> controller = container.Resolve&lt;<span
style="color: #2b91af">IController</span>&gt;();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.That(container.Kernel.ReleasePolicy.HasTrack(controller));</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.IsFalse(container.Kernel.ReleasePolicy.HasTrack(controller.Dependency));</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p></div><p></p></p><p>We request an IController instance, which is tracked by the container. The IController's Dependency property contains an IDependency instance, which was also created by the container. But as the last line of the test shows: the container does not track instances of the requested IController's dependencies.</p><p>So what does that mean? If the dependencies don't require any cleanup, then this is great. We simply need to release the requested component, and the component and its dependencies will all be eligible for Garbage Collection.</p><p>(Note 27/01/10: the following part is no longer relevant as of Castle Windsor 2.1)</p><p>But what happens when the dependencies need to be disposed? Let's take another look.</p><p>We modify the IDependency interface and MyDependency class so it looks like this:</p><p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">interface</span> <span
style="color: #2b91af">IDependency</span> : <span
style="color: #2b91af">IDisposable</span></p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">bool</span> Disposed { <span
style="color: blue">get</span>; <span
style="color: blue">set</span>; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">class</span> <span
style="color: #2b91af">MyDependency</span> : <span
style="color: #2b91af">IDependency</span></p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">bool</span> Disposed { <span
style="color: blue">get</span>; <span
style="color: blue">set</span>; }</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> Dispose()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Disposed = <span
style="color: blue">true</span>;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;&#160;&#160; }</p></div><p></p></p><p>Now let's see what happens with the Controller's dependencies when we release the Controller:</p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span
style="color: #2b91af">Test</span>]</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> ContainerDoesNotDisposeControllersDisposableDependencies()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> container = CreateContainer();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> controller = container.Resolve&lt;<span
style="color: #2b91af">IController</span>&gt;();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">var</span> dependency = controller.Dependency;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.That(container.Kernel.ReleasePolicy.HasTrack(controller));</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; container.Release(controller);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.IsFalse(container.Kernel.ReleasePolicy.HasTrack(controller));&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.IsFalse(container.Kernel.ReleasePolicy.HasTrack(dependency));</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.IsTrue(controller.Disposed);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Assert</span>.IsFalse(dependency.Disposed);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p></div><p>The container holds no references, but the Controller's Dependency instance is not disposed! Notice however that the Controller has been disposed by the container. As i've mentioned <a
href="http://davybrion.com/blog/2008/08/net-memory-management/">earlier</a>, if you own a reference to an IDisposable instance, you are responsible for properly disposing of that instance. So we modify the Controller's Dispose method so that it looks like this:</p><div
style="font-family: consolas; background: white; color: black; font-size: 10pt"><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">public</span> <span
style="color: blue">void</span> Dispose()</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Dependency.Dispose();</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Disposed = <span
style="color: blue">true</span>;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p></div><p>The previous test will now fail, because the Dependency will be properly disposed.</p><p>NOTE: i certainly don't recommend to implement your Dispose methods like i just did. This is just a simplified example. The proper way to implement the Disposable Pattern is discussed <a
href="http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/">here</a>.</p><p>Anyways, i hope it's clear now how you can make sure your IoC usage does not cause memory leaks, and that everything is properly disposed of.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F12%2Fthe-importance-of-releasing-your-components-through-windsor%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/"  data-text="The Importance Of Releasing Your Components Through Windsor" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/12/the-importance-of-releasing-your-components-through-windsor/feed/</wfw:commentRss> <slash:comments>13</slash:comments> </item> <item><title>Automanual Dependency Injection?</title><link>http://davybrion.com/blog/2008/06/automanual-dependency-injection/</link> <comments>http://davybrion.com/blog/2008/06/automanual-dependency-injection/#comments</comments> <pubDate>Mon, 16 Jun 2008 07:00:39 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[ASP.NET]]></category> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Inversion Of Control]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=144</guid> <description><![CDATA[I apologize in advance for using the term 'automanual' but if you've been reading this blog for a while you already know i completely suck at coming up with good names. So bear with me, and you'll probably understand what i mean as you work your way through this post. It really is pretty cool... [...]]]></description> <content:encoded><![CDATA[<p>I apologize in advance for using the term 'automanual' but if you've been reading this blog for a while you already know i completely suck at coming up with good names.  So bear with me, and you'll probably understand what i mean as you work your way through this post.  It really is pretty cool... i promise :p</p><p>I'm playing around with some <a
href="http://haacked.com/archive/2006/08/09/ASP.NETSupervisingControllerModelViewPresenterFromSchematicToUnitTestsToCode.aspx">supervising controller MVP</a> stuff using regular ASP.NET webforms.  Yes i know, i should be using ASP.NET MVC but i have a strict "i don't touch it before there's a final release"-policy when it comes to Microsoft products (as opposed to my "lemme just build the latest version of the trunk"-policy for various open source products). Anyways, what i'm trying to do is pretty simple.  I have a view (ProductList.aspx) which uses a supervising controller (ProductListController). The view (the aspx page) will notify the controller when it needs to do something through events. The controller will then do whatever it needs to do and it will send the data back to the view through properties of the view.  If that's not clear to you, read the post i linked to for a much better and detailed explanation.</p><p>Since ASP.NET automatically instantiates your aspx page, the easiest thing to do is to let the view create the controller and then pass itself as a parameter to the controller.  But the controller also has other dependencies, such as a service which exposes the business logic that we need for this screen. So i have two options: i either create the controller myself and provide all the dependencies, or i use an inversion of control container to create the controller and to wire up all the dependencies.  I don't want to have to modify my view code whenever i add/remove a dependency of the controller, so i go with the inversion of control container.</p><p>Suppose the constructor of the controller looks like this:</p><p><code></p><div
style="font-family: Consolas; font-size: 10pt; color: black; background: white;"><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">public</span> ProductListController(<span
style="color: #2b91af;">IProductList</span> view, <span
style="color: #2b91af;">IProductsService</span> productsService)</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">this</span>.view = view;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">this</span>.productsService = productsService;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>Here's where it gets tricky... since the view (which implements the IProductList interface) is asking the container to create a ProductListController, how can the container pass the correct IProductList dependency to the controller? We can't use the regular dependency look-up mechanisms because our controller actually needs the current view instance, but that view instance is asking the container to create the controller! By default, the container has no way whatsoever to resolve the IProductList dependency to the current view instance.  So basically, what we want to do in this case is to manually provide the view dependency, but still have the container automatically provide the IProductsService dependency (hence the term 'automanual' which you have to admit is starting to sound pretty good at this point, right?).  And of course, we want all of this to work automagically.</p><p>It turns out that Castle's Windsor actually does have some slick tricks to make this work. Here's how we can create the controller through the container from the view:</p><p><code></p><div
style="font-family: Consolas; font-size: 10pt; color: black; background: white;"><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: #2b91af;">IProductListController</span> controller =</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: #2b91af;">Container</span>.Resolve&lt;<span
style="color: #2b91af;">IProductListController</span>&gt;(<span
style="color: blue;">new</span> { view = <span
style="color: blue;">this</span> });</p></div><p></code></p><p>Told you it was slick! It's pretty easy actually... the parameter we pass to the Resolve method is an instance of an anonymous type with a view property.  We set the view property to the current aspx instance (using the 'this' keyword obviously) and Windsor is smart enough to figure out that this value should be used to satisfy the view dependency instead of using it's normal look-up mechanisms.  The result is that our controller has a reference to the current view, and its IProductsService reference is resolved as the container would typically resolve dependencies.  Pretty sweet.</p><p>Btw, i googled the term 'automanual' and sure enough, it already exists... but it's not really used in the context of writing code so if this thing sticks, remember where you heard it first <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /></p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F06%2Fautomanual-dependency-injection%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/06/automanual-dependency-injection/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/06/automanual-dependency-injection/"  data-text="Automanual Dependency Injection?" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/06/automanual-dependency-injection/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/06/automanual-dependency-injection/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/06/automanual-dependency-injection/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Windsor’s Interceptors and Performance, Part 2</title><link>http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance-part-2/</link> <comments>http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance-part-2/#comments</comments> <pubDate>Sat, 10 May 2008 09:55:14 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Inversion Of Control]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[castle]]></category> <category><![CDATA[windsor]]></category><guid
isPermaLink="false">http://ralinx.wordpress.com/?p=115</guid> <description><![CDATA[Gael Fraiteur's comment on my previous post made me realize that my performance test in the previous post wasn't all that good... Let's go back to the part of the code that performed the test: &#160;&#160;&#160; &#160;&#160;&#160; [Test] &#160;&#160;&#160; &#160;&#160;&#160; public void TestDummyPerformance() &#160;&#160;&#160; &#160;&#160;&#160; { &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; Time(() =&#62; CallMethodXAmountOfTimes(new Dummy(), 1000000)); &#160;&#160;&#160; [...]]]></description> <content:encoded><![CDATA[<p><a
href="http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance/#comment-222">Gael Fraiteur's comment</a> on my previous post made me realize that my performance test in the previous post wasn't all that good...</p><p>Let's go back to the part of the code that performed the test:</p><p><code></p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; [<span
style="color:#2b91af;">Test</span>]</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">void</span> TestDummyPerformance()</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Time(() =&gt; CallMethodXAmountOfTimes(<span
style="color:blue;">new</span> <span
style="color:#2b91af;">Dummy</span>(), 1000000));</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Time(() =&gt; CallMethodXAmountOfTimes(<span
style="color:#2b91af;">Container</span>.Resolve&lt;<span
style="color:#2b91af;">IDummy</span>&gt;(), 1000000));</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">private</span> <span
style="color:blue;">void</span> CallMethodXAmountOfTimes(<span
style="color:#2b91af;">IDummy</span> dummy, <span
style="color:blue;">int</span> times)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">for</span> (<span
style="color:blue;">int</span> i = 0; i &lt; times; i++)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; dummy.DoSomething();&nbsp;&nbsp;&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">private</span> <span
style="color:blue;">void</span> Time(<span
style="color:#2b91af;">Action</span> action)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:#2b91af;">DateTime</span> before = <span
style="color:#2b91af;">DateTime</span>.Now;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; action();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:#2b91af;">Console</span>.WriteLine(<span
style="color:#a31515;">"Time elapsed : "</span> + (<span
style="color:#2b91af;">DateTime</span>.Now - before));</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>The Time method has an Action parameter, which basically points to a block of code that will be executed when you call it. In this case the action() line causes the block of code to be executed. I have a habit of trying to write concise code, so the instantiation of the dummy instance is in both cases inlined in the block of code that will be executed by the Time() method. As Gael points out in his comment, Windsor generates a proxy when you request a component that has an interceptor assigned to it, and this is obviously a more expensive operation than simply new-ing a concrete instance.  So this extra cost was reflected in the results as well.</p><p>If we change the test code to this:</p><p><code></p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; [<span
style="color:#2b91af;">Test</span>]</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">void</span> TestDummyPerformance()</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">var</span> dummy = <span
style="color:blue;">new</span> <span
style="color:#2b91af;">Dummy</span>();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Time(() =&gt; CallMethodXAmountOfTimes(dummy, 1000000));</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">var</span> interceptedDummy = <span
style="color:#2b91af;">Container</span>.Resolve&lt;<span
style="color:#2b91af;">IDummy</span>&gt;();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Time(() =&gt; CallMethodXAmountOfTimes(interceptedDummy, 1000000));</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>Now, the difference is not so big as it was in the previous test:
Time elapsed : 00:00:00.0100144
Time elapsed : 00:00:00.2403456</p><p>Again, this is for one million method calls... in a real world scenario, you probably won't notice the performance hit.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F05%2Fwindsors-interceptors-and-performance-part-2%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance-part-2/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance-part-2/"  data-text="Windsor’s Interceptors and Performance, Part 2" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance-part-2/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance-part-2/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance-part-2/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Windsor&#8217;s Interceptors and Performance</title><link>http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance/</link> <comments>http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance/#comments</comments> <pubDate>Fri, 09 May 2008 22:13:58 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Inversion Of Control]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[castle]]></category> <category><![CDATA[windsor]]></category><guid
isPermaLink="false">http://ralinx.wordpress.com/?p=114</guid> <description><![CDATA[As i mentioned in a previous post, Windsor's Interceptors are a great way to dynamically add behavior to a class. But what does it cost? There's a lot of stuff going on behind to scenes to make that 'magic' work and surely, there's a performance penalty involved somewhere. I wanted to see what the cost [...]]]></description> <content:encoded><![CDATA[<p>As i mentioned in <a
href="http://davybrion.com/blog/2008/05/adding-behavior-without-modifying-existing-code-with-windsor/">a previous post</a>, Windsor's Interceptors are a great way to dynamically add behavior to a class.  But what does it cost? There's a lot of stuff going on behind to scenes to make that 'magic' work and surely, there's a performance penalty involved somewhere.</p><p>I wanted to see what the cost of this approach is, so i created the following interface and class:</p><p><code></p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">interface</span> <span
style="color:#2b91af;">IDummy</span></p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">void</span> DoSomething();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">class</span> <span
style="color:#2b91af;">Dummy</span> : <span
style="color:#2b91af;">IDummy</span></p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">void</span> DoSomething() {}</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>Nothing special there... just a class with a method that doesn't do anything. Combine that with an interceptor that doesn't do anything:</p><p><code></p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">class</span> <span
style="color:#2b91af;">DummyInterceptor</span> : Castle.Core.Interceptor.<span
style="color:#2b91af;">IInterceptor</span></p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">void</span> Intercept(<span
style="color:#2b91af;">IInvocation</span> invocation)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:green;">// do nothing, just proceed with the original call</span></p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; invocation.Proceed();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>And then we configure the component and the interceptor like this:</p><p><code></p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">component</span><span
style="color:blue;"> </span><span
style="color:red;">id</span><span
style="color:blue;">=</span>"<span
style="color:blue;">DummyInterceptor</span>"<span
style="color:blue;"> </span><span
style="color:red;">service</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.DummyInterceptor, Components</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">type</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.DummyInterceptor, Components</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">lifestyle</span><span
style="color:blue;">=</span>"<span
style="color:blue;">transient</span>"<span
style="color:blue;"> /&gt;</span></p></div><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">component</span><span
style="color:blue;"> </span><span
style="color:red;">id</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Dummy</span>"<span
style="color:blue;"> </span><span
style="color:red;">service</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.IDummy, Components</span>"<span
style="color:blue;"> </span><span
style="color:red;">type</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.Dummy, Components</span>"<span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">interceptors</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">interceptor</span><span
style="color:blue;">&gt;</span>${DummyInterceptor}<span
style="color:blue;">&lt;/</span><span
style="color:#a31515;">interceptor</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">interceptors</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">component</span><span
style="color:blue;">&gt;</span></p></div><p></code></p><p>So what do we have now? We have a component which has a method that doesn't do anything. And we've assigned an interceptor that doesn't do anything... it just executes the original call without adding any behavior. Pretty useless, right? Right, but this is ideal to compare the runtime cost of merely intercepting calls to components. So the differences you'll see below are without adding the extra behavior to your components. The differences you'll see below are purely because each call is intercepted.</p><p>This is the code i used to test the difference:</p><p><code></p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; [<span
style="color:#2b91af;">Test</span>]</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">void</span> TestDummyPerformance()</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Time(() =&gt; CallMethodXAmountOfTimes(<span
style="color:blue;">new</span> <span
style="color:#2b91af;">Dummy</span>(), 1000000));</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Time(() =&gt; CallMethodXAmountOfTimes(<span
style="color:#2b91af;">Container</span>.Resolve&lt;<span
style="color:#2b91af;">IDummy</span>&gt;(), 1000000));</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">private</span> <span
style="color:blue;">void</span> CallMethodXAmountOfTimes(<span
style="color:#2b91af;">IDummy</span> dummy, <span
style="color:blue;">int</span> times)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">for</span> (<span
style="color:blue;">int</span> i = 0; i &lt; times; i++)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; dummy.DoSomething();&nbsp;&nbsp;&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">private</span> <span
style="color:blue;">void</span> Time(<span
style="color:#2b91af;">Action</span> action)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:#2b91af;">DateTime</span> before = <span
style="color:#2b91af;">DateTime</span>.Now;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; action();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:#2b91af;">Console</span>.WriteLine(<span
style="color:#a31515;">"Time elapsed : "</span> + (<span
style="color:#2b91af;">DateTime</span>.Now - before));</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>First, we call the DoSomething method on a regular Dummy instance 1 million times. The time that takes is written to the Console. Then we call the DoSomething method (again, 1 million times) on an IDummy instance provided by the container, which has our interceptor attached to it (note: when you do not have an interceptor attached, there is NO runtime penalty!).</p><p>The output of the test (on my machine) is the following:</p><p>Time elapsed : 00:00:00.0100144
Time elapsed : 00:00:00.5808352</p><p>As you can see, the second time (using the intercepted instance) is significantly slower than using a concrete instance.  But honestly, this is after calling the method <strong>one million times</strong>. And it only takes about half a second (on a virtualized Windows XP running on a cheap Macbook <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ) to call this method one million times.  In a real-world scenario, you probably won't notice any performance hit unless the code that is intercepted is in a long, tight loop or something like that.</p><p>Having said that, i do think using the interceptor approach should be a temporary action in most cases. If you have to debug weird issues, i think adding an extensive logging/tracing interceptor to your components can be extremely valuable without having to pollute your code with logging/tracing statements.  But if you want certain behavior to be added to your classes without it being configurable, there certainly are better options to use. <a
href="http://www.postsharp.org/">PostSharp</a> is a library which enables <a
href="http://en.wikipedia.org/wiki/Aspect_oriented_programming">Aspect Oriented Programming</a> without performance penalties. This approach basically allows you to add specific behavior to methods or classes by placing attributes on them.  PostSharp will then modify the compiled byte-code to add the 'aspects' (the behavior that you want to add) to the real code. I'll write a post about this approach soon <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /></p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F05%2Fwindsors-interceptors-and-performance%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance/"  data-text="Windsor&#8217;s Interceptors and Performance" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/05/windsors-interceptors-and-performance/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Adding behavior without modifying existing code with Windsor</title><link>http://davybrion.com/blog/2008/05/adding-behavior-without-modifying-existing-code-with-windsor/</link> <comments>http://davybrion.com/blog/2008/05/adding-behavior-without-modifying-existing-code-with-windsor/#comments</comments> <pubDate>Sun, 04 May 2008 20:18:27 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Aspect Oriented Programming]]></category> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Inversion Of Control]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[castle]]></category> <category><![CDATA[windsor]]></category><guid
isPermaLink="false">http://ralinx.wordpress.com/?p=104</guid> <description><![CDATA[The Windsor container makes it quite easy to add behavior to components, without having to modify their implementation. This could be useful in many scenario's. Suppose you need to log whenever a method from our OrderRepository class is called. But we should be able to turn the logging on and off whenever we want. Preferably, [...]]]></description> <content:encoded><![CDATA[<p>The Windsor container makes it quite easy to add behavior to components, without having to modify their implementation. This could be useful in many scenario's. Suppose you need to log whenever a method from our OrderRepository class is called.  But we should be able to turn the logging on and off whenever we want.  Preferably, without having to modify the code all the time. Now, you could easily write a logger class that checks for a configuration setting and only logs when needed. This approach would definitely work. But then there's logging code all over the OrderRepository class and in most cases, it's not even necessary since they only want to be able to log under certain circumstances. Should the OrderRepository class really care about the logging? Why litter the code with logging statements?</p><p>If you're using the Windsor container, you could easily add logging behavior to the OrderRepository class without having to change any of the existing code. Windsor has this concept of Interceptors. Basically you can assign an interceptor to any component and you can plug in your custom behavior when the component is called. Lets get into an example... Since logging is such a common requirement, we decided to put it in one class instead of littering our entire code base with logging statements. So we wrote the following class:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">class</span> <span
style="color:#2b91af;">LoggingInterceptor</span> : Castle.Core.Interceptor.<span
style="color:#2b91af;">IInterceptor</span></p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">private</span> <span
style="color:blue;">readonly</span> <span
style="color:#2b91af;">ILogger</span> logger;</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> LoggingInterceptor(<span
style="color:#2b91af;">ILogger</span> logger)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">this</span>.logger = logger;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">void</span> Intercept(<span
style="color:#2b91af;">IInvocation</span> invocation)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">string</span> methodName =</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; invocation.TargetType.FullName + <span
style="color:#a31515;">"."</span> + invocation.GetConcreteMethod().Name;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Log(<span
style="color:#a31515;">"Entering method: "</span> + methodName);</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; invocation.Proceed();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Log(<span
style="color:#a31515;">"Leaving mehod: "</span> + methodName);</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">private</span> <span
style="color:blue;">void</span> Log(<span
style="color:blue;">string</span> line)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; logger.WriteLine(<span
style="color:#2b91af;">DateTime</span>.Now.TimeOfDay + <span
style="color:#a31515;">" "</span> + line);</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; }</p></div><p>This class implements the IInterceptor interface by implementing the Intercept method. When that method is called we simply construct the full method name, log when we enter the method, call the original method and then we log again when we leave the method.  Nothing more, nothing less. Also notice how the LoggingInterceptor has a dependency on an ILogger instance. That instance will be injected by the container as well.</p><p>So first of all, we need to define the ILogger and LoggingInterceptor components:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">component</span><span
style="color:blue;"> </span><span
style="color:red;">id</span><span
style="color:blue;">=</span>"<span
style="color:blue;">ILogger</span>"<span
style="color:blue;"> </span><span
style="color:red;">service</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.ILogger, Components</span>"<span
style="color:blue;"> </span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">type</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.Logger, Components</span>"<span
style="color:blue;"> /&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">component</span><span
style="color:blue;"> </span><span
style="color:red;">id</span><span
style="color:blue;">=</span>"<span
style="color:blue;">LoggingInterceptor</span>"<span
style="color:blue;"> </span><span
style="color:red;">service</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.LoggingInterceptor, Components</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">type</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.LoggingInterceptor, Components</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">lifestyle</span><span
style="color:blue;">=</span>"<span
style="color:blue;">transient</span>"<span
style="color:blue;"> /&gt;</span></p></div><p>Right... so now we need to add this behavior to the OrderRepository class. This only requires modifying the registration of the IOrderRepository component:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">component</span><span
style="color:blue;"> </span><span
style="color:red;">id</span><span
style="color:blue;">=</span>"<span
style="color:blue;">IOrderRepository</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">service</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.IOrderRepository, Components</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">type</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.OrderRepository, Components</span>"<span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">interceptors</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">interceptor</span><span
style="color:blue;">&gt;</span>${LoggingInterceptor}<span
style="color:blue;">&lt;/</span><span
style="color:#a31515;">interceptor</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">interceptors</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">component</span><span
style="color:blue;">&gt;</span></p></div><p>What we basically did was tell Windsor that whenever an IOrderRepository is requested, we should return an instance of OrderRepository and each time a method of that instance is called, it needs to be intercepted by our LoggingInterceptor.</p><p>So if we simply call the IOrderRepository methods like this (obviously these are dummy calls without real parameters and we're also ignoring return values):</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">var</span> repository = <span
style="color:#2b91af;">Container</span>.Resolve&lt;<span
style="color:#2b91af;">IOrderRepository</span>&gt;();</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; repository.GetAll();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; repository.FindOne(<span
style="color:blue;">new</span> <span
style="color:#2b91af;">Criteria</span>());</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; repository.FindMany(<span
style="color:blue;">new</span> <span
style="color:#2b91af;">Criteria</span>());</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; repository.GetById(<span
style="color:#2b91af;">Guid</span>.Empty);</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; repository.Store(<span
style="color:blue;">null</span>);</p></div><p>The following output is logged:</p><p><pre>
21:53:42.6942016 Entering method: Components.OrderRepository.GetAll
21:53:42.6942016 Leaving mehod: Components.OrderRepository.GetAll
21:53:42.6942016 Entering method: Components.OrderRepository.FindOne
21:53:42.6942016 Leaving mehod: Components.OrderRepository.FindOne
21:53:42.6942016 Entering method: Components.OrderRepository.FindMany
21:53:42.6942016 Leaving mehod: Components.OrderRepository.FindMany
21:53:42.7042160 Entering method: Components.OrderRepository.GetById
21:53:42.7042160 Leaving mehod: Components.OrderRepository.GetById
21:53:42.7042160 Entering method: Components.OrderRepository.Store
21:53:42.7042160 Leaving mehod: Components.OrderRepository.Store
</pre></p><p>And we didn't have to change the OrderRepository implementation. In fact, we can use our LoggingInterceptor wherever we like, as long as the component to be logged is registered with Windsor.  And we can easily switch between logging or no logging by switching config files.</p><p>Obviously, this was just a really simple example but i hope you realize how powerful this technique is and how far you can go with this.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F05%2Fadding-behavior-without-modifying-existing-code-with-windsor%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/05/adding-behavior-without-modifying-existing-code-with-windsor/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/05/adding-behavior-without-modifying-existing-code-with-windsor/"  data-text="Adding behavior without modifying existing code with Windsor" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/05/adding-behavior-without-modifying-existing-code-with-windsor/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/05/adding-behavior-without-modifying-existing-code-with-windsor/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/05/adding-behavior-without-modifying-existing-code-with-windsor/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Providing configuration data with Windsor</title><link>http://davybrion.com/blog/2008/05/providing-configuration-data-with-windsor/</link> <comments>http://davybrion.com/blog/2008/05/providing-configuration-data-with-windsor/#comments</comments> <pubDate>Fri, 02 May 2008 14:08:50 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Inversion Of Control]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[castle]]></category> <category><![CDATA[windsor]]></category><guid
isPermaLink="false">http://ralinx.wordpress.com/?p=100</guid> <description><![CDATA[Some classes need configuration data to function properly. This configuration data could be a database connection string, a path, a hostname, a network port, whatever. You typically deal with this by putting the configuration data in your app.config or web.config... either through a Settings file or in the AppSettings or maybe you've created your own [...]]]></description> <content:encoded><![CDATA[<p>Some classes need configuration data to function properly. This configuration data could be a database connection string, a path, a hostname, a network port, whatever. You typically deal with this by putting the configuration data in your app.config or web.config... either through a Settings file or in the AppSettings or maybe you've created your own configuration section or whatever.  And in most cases, when a class needs this data, it simply retrieves it from the Configuration class or the class that was created through your Settings class.</p><p>By doing this, you actually create a strong dependency between your class, and the object that provides the configuration data. But you're not really dependent on the object providing the data, since you really only need a bit of data to function.  So why not treat the data itself as a dependency?</p><p>Let's use our <a
href="http://davybrion.com/blog/2008/04/introduction-to-ioc-with-windsor/">previous example</a>.  The OrderDataAccessor class will retrieve Orders from a database. In order to do that, it needs a connection string.  Instead of letting the OrderDataAccessor class retrieve that connection string from a config file itself, we'll modify the constructor so that each instance retrieves the connection string when it is created:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">private</span> <span
style="color:blue;">readonly</span> <span
style="color:blue;">string</span> _connectionString;</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> OrderDataAccessor(<span
style="color:blue;">string</span> connectionString)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _connectionString = connectionString;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p>If the container now needs to create an OrderDataAccessor instance, we get the following exception:</p><p><pre>
Castle.MicroKernel.Resolvers.DependencyResolverException : Could not resolve non-optional
dependency for 'Components.OrderDataAccessor' (Components.OrderDataAccessor).
Parameter 'connectionString' type 'System.String'
</pre></p><p>Which makes sense, since we haven't told the container about this 'dependency' yet. Since we're dealing with configuration data now, it's probably better to move our Windsor configuration to a config file as well.  First we'll define the castle configuration section in our app.config:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;"><span
style="color:blue;">&nbsp; &lt;</span><span
style="color:#a31515;">configSections</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">section</span><span
style="color:blue;"> </span><span
style="color:red;">name</span><span
style="color:blue;">=</span>"<span
style="color:blue;">castle</span>"<span
style="color:blue;"> </span><span
style="color:red;">type</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor</span>"<span
style="color:blue;"> /&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &lt;/</span><span
style="color:#a31515;">configSections</span><span
style="color:blue;">&gt;</span></p></div><p>Then we configure our components:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;"><span
style="color:blue;">&nbsp; &lt;</span><span
style="color:#a31515;">castle</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">components</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">component</span><span
style="color:blue;"> </span><span
style="color:red;">id</span><span
style="color:blue;">=</span>"<span
style="color:blue;">IOrderDataAccessor</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">service</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.IOrderDataAccessor, Components</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">type</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.OrderDataAccessor, Components</span>"<span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">parameters</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">connectionString</span><span
style="color:blue;">&gt;</span>myConnectionString<span
style="color:blue;">&lt;/</span><span
style="color:#a31515;">connectionString</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">parameters</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">component</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">component</span><span
style="color:blue;"> </span><span
style="color:red;">id</span><span
style="color:blue;">=</span>"<span
style="color:blue;">IOrderRepository</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">service</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.IOrderRepository, Components</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">type</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.OrderRepository, Components</span>"<span
style="color:blue;"> /&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">components</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &lt;/</span><span
style="color:#a31515;">castle</span><span
style="color:blue;">&gt;</span></p></div><p>And that's it... Whenever the container instantiates an OrderDataAccessor instance, it will pass 'myConnectionString' to the connectionString parameter.</p><p>There's one issue with this though... In a real system, you'd have more than one DataAccessor class, and having to specify the connectionString for each one of them would be a prime example of suckage. So let's modify our config file a little bit:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;"><span
style="color:blue;">&nbsp; &lt;</span><span
style="color:#a31515;">castle</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">properties</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">connectionString</span><span
style="color:blue;">&gt;</span>myConnectionString<span
style="color:blue;">&lt;/</span><span
style="color:#a31515;">connectionString</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">properties</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">components</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">component</span><span
style="color:blue;"> </span><span
style="color:red;">id</span><span
style="color:blue;">=</span>"<span
style="color:blue;">IOrderDataAccessor</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">service</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.IOrderDataAccessor, Components</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">type</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.OrderDataAccessor, Components</span>"<span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">parameters</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">connectionString</span><span
style="color:blue;">&gt;</span>#{connectionString}<span
style="color:blue;">&lt;/</span><span
style="color:#a31515;">connectionString</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">parameters</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">component</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span
style="color:#a31515;">component</span><span
style="color:blue;"> </span><span
style="color:red;">id</span><span
style="color:blue;">=</span>"<span
style="color:blue;">IOrderRepository</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">service</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.IOrderRepository, Components</span>"</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span
style="color:red;">type</span><span
style="color:blue;">=</span>"<span
style="color:blue;">Components.OrderRepository, Components</span>"<span
style="color:blue;"> /&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &nbsp; &lt;/</span><span
style="color:#a31515;">components</span><span
style="color:blue;">&gt;</span></p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;"><span
style="color:blue;">&nbsp; &lt;/</span><span
style="color:#a31515;">castle</span><span
style="color:blue;">&gt;</span></p></div><p>That's better... Now we can just refer to the connectionString whenever we need it so we'd only have to modify it in one place.</p><p>Keep in mind that if you put the Windsor configuration in your app.config/web.config file, you need to instantiate the container like this:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container = <span
style="color:blue;">new</span> <span
style="color:#2b91af;">WindsorContainer</span>(<span
style="color:blue;">new</span> <span
style="color:#2b91af;">XmlInterpreter</span>());</p></div><p>So as you can see, you can also use the IoC container to keep dependencies on configuration-providing-classes completely out of your code by 'promoting' the required configuration data to actual dependencies of your components.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F05%2Fproviding-configuration-data-with-windsor%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/05/providing-configuration-data-with-windsor/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/05/providing-configuration-data-with-windsor/"  data-text="Providing configuration data with Windsor" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/05/providing-configuration-data-with-windsor/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/05/providing-configuration-data-with-windsor/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/05/providing-configuration-data-with-windsor/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Windsor and component instance lifetimes</title><link>http://davybrion.com/blog/2008/05/windsor-and-component-instance-lifetimes/</link> <comments>http://davybrion.com/blog/2008/05/windsor-and-component-instance-lifetimes/#comments</comments> <pubDate>Thu, 01 May 2008 15:39:53 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Inversion Of Control]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[castle]]></category> <category><![CDATA[windsor]]></category><guid
isPermaLink="false">http://ralinx.wordpress.com/?p=99</guid> <description><![CDATA[In my previous Windsor post i showed you how you can use the Windsor container to manage your components and their dependencies. Since it was merely an introductory post on Windsor, i only showed how you can use it to handle dependencies. But there's a lot more you can do with it, and that you [...]]]></description> <content:encoded><![CDATA[<p>In my previous <a
href="http://davybrion.com/blog/2008/04/introduction-to-ioc-with-windsor/">Windsor post</a> i showed you how you can use the Windsor container to manage your components and their dependencies.  Since it was merely an introductory post on Windsor, i only showed how you can use it to handle dependencies. But there's a lot more you can do with it, and that you should know about.</p><p>One thing you'll definitely need to know to properly use Windsor, is that of component instance lifetimes. After all, you want the container to manage your components and their dependencies. But there's more to the management of components than merely filling in dependencies. Should the container return a new instance of a component? Should it return an already existing instance? How do you control that behavior without having clients know about it? After all, should clients of components really know about that? Is that not an implementation detail that might be better of being properly encapsulated from clients?</p><p>Windsor allows you to register components with specific lifestyles. These are the lifestyles you can use:</p><ul><li>Singleton: components are instantiated once, and shared between all clients</li><li>Transient: components are created on demand</li><li>PerWebRequest: components are created once per Http Request</li><li>Thread: components have a unique instance per thread</li><li>Pooled: Optimization of transient components that keeps instance in a pool instead of always creating them</li><li>Custom: allows you to specify a custom lifestyle... you'd have to specify a type that implements the ILifeStyleManager interface</li></ul><p>The Singleton lifestyle is actually the default. I'm not so happy with that being the default, but oh well... If we continue with our previous sample, we can verify that Singleton is indeed the default lifestyle for a registered component.  Suppose the component is registered like this:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponent&lt;<span
style="color:#2b91af;">IOrderRepository</span>, <span
style="color:#2b91af;">OrderRepository</span>&gt;();</p></div><p>Then the following test would pass:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">var</span> r1 = <span
style="color:#2b91af;">Container</span>.Resolve&lt;<span
style="color:#2b91af;">IOrderRepository</span>&gt;();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">var</span> r2 = <span
style="color:#2b91af;">Container</span>.Resolve&lt;<span
style="color:#2b91af;">IOrderRepository</span>&gt;();</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:#2b91af;">Assert</span>.That(ReferenceEquals(r1, r2));</p></div><p>But if we change the registration to this:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponentWithLifestyle&lt;<span
style="color:#2b91af;">IOrderRepository</span>, <span
style="color:#2b91af;">OrderRepository</span>&gt;(<span
style="color:#2b91af;">LifestyleType</span>.Transient);</p></div><p>Then the test obviously fails because both requests to get an IOrderRepository instance will create a new OrderRepository instance.</p><p>You might be wondering what happens when you define a component as a singleton, but one of its dependencies is transient:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponentWithLifestyle&lt;<span
style="color:#2b91af;">IOrderDataAccessor</span>, <span
style="color:#2b91af;">OrderDataAccessor</span>&gt;(<span
style="color:#2b91af;">LifestyleType</span>.Transient);</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponentWithLifestyle&lt;<span
style="color:#2b91af;">IOrderRepository</span>, <span
style="color:#2b91af;">OrderRepository</span>&gt;(<span
style="color:#2b91af;">LifestyleType</span>.Singleton);</p></div><p>The answer is pretty straightforward: when you request an instance of type IOrderRepository the first time, it will create a new IOrderAccessor instance as well and pass it to the OrderRepository constructor. The second time you request an instance of type IOrderRepository, the container already has the singleton instance cached, so a new IOrderAccessor instance is not created.</p><p>If you really want this behavior (a new IOrderDataAccessor instance whenever the singleton IOrderRepository is requested) you can get it working pretty easily. Right now, our OrderRepository implementation uses Constructor Injection:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">private</span> <span
style="color:#2b91af;">IOrderDataAccessor</span> _accessor;</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> OrderRepository(<span
style="color:#2b91af;">IOrderDataAccessor</span> accessor)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _accessor = accessor;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p>If we add Setter Injection as well the container will use the setter injector when we request the IOrderRepository instance after it has already been created:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:#2b91af;">IOrderDataAccessor</span> DataAccessor</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">set</span> { _accessor = <span
style="color:blue;">value</span>; }</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p>Because we have both Constructor Injection and Setter Injection, the container will supply a new IOrderDataAccessor when the OrderRepository instance is created. And when it is requested again after its creation, the container will supply a new IOrderDataAccessor instance to the OrderRepository using the setter of the dependency.</p><p>It's nice to know that this is possible, but i wouldn't recommend this approach... It's very confusing and would certainly cause problems in multi-threaded scenarios.  You're better off injecting an IOrderDataAccessorFactory object when the repository is created, and then let the repository request a new IOrderDataAccessor instance to be used locally whenever it's needed (as in: as a local variable during method execution, but certainly not as a field of the class).</p><p>There's also the other way around of course... suppose the dependency is configured as a singleton, and the component to be used is configured to have the Transient lifestyle.  The singleton dependency will only be created once, and every time you request a transient component that is dependent on a singleton component, the container injects the singleton instance in the transient component.</p><p>By now, I hope you realize that an Inversion Of Control Container is about more than merely Dependency Injection and increasing testability.  There's most certainly a lot more to it than that <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . I have a few more posts coming up about how using an IoC container can make your life as a developer easier.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F05%2Fwindsor-and-component-instance-lifetimes%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/05/windsor-and-component-instance-lifetimes/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/05/windsor-and-component-instance-lifetimes/"  data-text="Windsor and component instance lifetimes" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/05/windsor-and-component-instance-lifetimes/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/05/windsor-and-component-instance-lifetimes/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/05/windsor-and-component-instance-lifetimes/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Introduction to IoC with Windsor</title><link>http://davybrion.com/blog/2008/04/introduction-to-ioc-with-windsor/</link> <comments>http://davybrion.com/blog/2008/04/introduction-to-ioc-with-windsor/#comments</comments> <pubDate>Tue, 29 Apr 2008 21:35:24 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Castle Windsor]]></category> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Inversion Of Control]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[testing]]></category> <category><![CDATA[castle]]></category> <category><![CDATA[windsor]]></category><guid
isPermaLink="false">http://ralinx.wordpress.com/?p=97</guid> <description><![CDATA[As you may or may not know, i'm a bit of a fan of dependency injection. If you're only using it on a small scale, you don't really need any tools to use the technique. But once you're used to this design technique, you'll quickly start using it in many places of your code. If [...]]]></description> <content:encoded><![CDATA[<p>As you may or may not know, i'm a bit of a fan of <a
href="http://davybrion.com/blog/2007/07/introduction-to-dependency-injection/">dependency injection</a>.  If you're only using it on a small scale, you don't really need any tools to use the technique.  But once you're used to this design technique, you'll quickly start using it in many places of your code. If you do, it quickly becomes cumbersome to deal with the real instances of your runtime dependencies manually. This is where tools like Inversion Of Control (IoC) containers come in to play. There are a few solid containers available for the .NET world, and even Microsoft has released their <a
href="http://www.codeplex.com/unity">own container</a>.  Basically, what the IoC container does for you, is take care of providing dependencies to components in a flexible and customizable way. It allows clients to remain completely oblivious to the dependencies of components they use.  This makes it easy to change components without having to modify client code. Not to mention the fact that your components are a lot easier to test, since you can simply inject fake dependencies during your tests.</p><p>How about some code to demonstrate? Suppose we have a class called OrderRepository which exposes methods such as GetById, GetAll, FindOne, FindMany and Store. Obviously, the OrderRepository has a dependency on a class that can actually communicate with some kind of physical datastore, either a database or an xml file or whatever.  Either way, it needs another object to access the Order data. Suppose we have an OrderAccessor class which implements an IOrderAccessor interface.  The interface declares all the methods we need to retrieve or store our Orders.  So our OrderRepository would need to communicate with an object that implements the IOrderAccessor interface.  Instead of letting the OrderRepository instantiate that object itself, it will receive it as a parameter in it's constructor:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">private</span> <span
style="color:blue;">readonly</span> <span
style="color:#2b91af;">IOrderDataAccessor</span> _accessor;</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> OrderRepository(<span
style="color:#2b91af;">IOrderDataAccessor</span> accessor)</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _accessor = accessor;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p>This makes it easy to test the OrderRepository class, and it's also easy to make it use different implementations of IOrderDataAccessor later on, should we need to.  Now obviously, you really don't want to do this when you need to instantiate the OrderRepository in your production code:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;"><span
style="color:#2b91af;">OrderRepository</span> repo = <span
style="color:blue;">new</span> <span
style="color:#2b91af;">OrderRepository</span>(<span
style="color:blue;">new</span> <span
style="color:#2b91af;">OrderDataAccessor</span>());</p></div><p>As a consumer of the OrderRepository, you shouldn't need to know what its dependencies are and you most certainly shouldn't need to pass the right dependencies into the constructor.  Instead, you just want a valid instance of OrderRepository. You really don't care how it was constructed, which dependencies it has and how they're provided.  You just need to be able to use it. That's all.  This is where the IoC container comes in to help you.  Suppose we wrap the IoC container in a Container class that has a few static methods to help you with instantiating instances of types.  We could then do this:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;"><span
style="color:#2b91af;">OrderRepository</span> repository = <span
style="color:#2b91af;">Container</span>.Resolve&lt;<span
style="color:#2b91af;">OrderRepository</span>&gt;();</p></div><p>That would leave you with a valid OrderRepository instance... one that has a usable IOrderDataAccessor but you don't even know about it, nor do you care how it got there. In other words, you can use the OrderRepository without knowing anything about its underlying implementation.</p><p>Let's take a look at the implementation of the Container class:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">static</span> <span
style="color:blue;">class</span> <span
style="color:#2b91af;">Container</span></p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">private</span> <span
style="color:blue;">static</span> <span
style="color:blue;">readonly</span> <span
style="color:#2b91af;">IWindsorContainer</span> _container;</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">static</span> Container()</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container = <span
style="color:blue;">new</span> <span
style="color:#2b91af;">WindsorContainer</span>();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponent&lt;<span
style="color:#2b91af;">IOrderDataAccessor</span>, <span
style="color:#2b91af;">OrderDataAccessor</span>&gt;();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponent&lt;<span
style="color:#2b91af;">OrderRepository</span>&gt;();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">static</span> T Resolve&lt;T&gt;()</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">return</span> _container.Resolve&lt;T&gt;();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; }</p></div><p>It just uses a static instance of Windor's Container and it registers the types we need... let's examine the following line:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">_container.AddComponent&lt;<span
style="color:#2b91af;">IOrderDataAccessor</span>, <span
style="color:#2b91af;">OrderDataAccessor</span>&gt;();</p></div><p>this basically sets up the container to return a new instance of OrderDataAccessor whenever an instance of IOrderDataAcessor is requested.</p><p>We still have to make sure the Windsor container knows about the OrderRepository class by adding it as a known component like this:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponent&lt;<span
style="color:#2b91af;">OrderRepository</span>&gt;();</p></div><p>By doing this, the Windsor container will inspect the type (in this case, OrderRepository) and it will see that its constructor requires an IOrderDataAccessor instance. We 'registered' the IOrderDataAccessor type with the container to return an instance of the OrderDataAccessor type. So basically, whenever someone asks the container to return an instance of an OrderRepository class, the container knows to instantiate an OrderDataAccessor instance to pass along as the required IOrderDataAccessor object to the OrderRepository constructor.</p><p>At this point, you may be wondering: "Why go through all this trouble to register the concrete implementation of IOrderDataAccessor to be used in code? We could just as well instantiate the type ourselves!".  That's certainly true.  The code would be slightly uglier, but you'd get the same behavior.  Of course, the Windsor container supports XML configuration (either in the app.config or web.config or in a custom configuration file) as well as explicit configuration through code. So you can configure the container through code explicitly, but if there is a config file present, the container will use that configuration instead of the one provided through code.  So you could define the defaults in code, and should you need to change it later on, you can just provide a config file.</p><p>You know what bothers me about our current implementation? We're still communicating with an OrderRepository instance. If we wanna be really flexible, it would be better if we were communicating with an object that implemented an IOrderRepository interface.  So let's just define the following interface:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">interface</span> <span
style="color:#2b91af;">IOrderRepository</span></p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:#2b91af;">Order</span> GetById(<span
style="color:#2b91af;">Guid</span> id);</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:#2b91af;">IEnumerable</span>&lt;<span
style="color:#2b91af;">Order</span>&gt; GetAll();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:#2b91af;">Order</span> FindOne(<span
style="color:#2b91af;">Criteria</span> criteria);</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:#2b91af;">IEnumerable</span>&lt;<span
style="color:#2b91af;">Order</span>&gt; FindMany(<span
style="color:#2b91af;">Criteria</span> criteria);</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">void</span> Store(<span
style="color:#2b91af;">Order</span> order);</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; }</p></div><p>After all, that's all we care about as consumers of a IOrderRepository type. We shouldn't really care about the concrete implementation.  We just need an interface to program to.  So let's change the OrderRepository definition to this:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; <span
style="color:blue;">public</span> <span
style="color:blue;">class</span> <span
style="color:#2b91af;">OrderRepository</span> : <span
style="color:#2b91af;">IOrderRepository</span></p></div><p>And then when we configure our IoC container we do it like this:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">static</span> Container()</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container = <span
style="color:blue;">new</span> <span
style="color:#2b91af;">WindsorContainer</span>();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponent&lt;<span
style="color:#2b91af;">IOrderDataAccessor</span>, <span
style="color:#2b91af;">OrderDataAccessor</span>&gt;();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponent&lt;<span
style="color:#2b91af;">IOrderRepository</span>, <span
style="color:#2b91af;">OrderRepository</span>&gt;();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p>Now we can no longer ask the contianer for an OrderRepository interface. But we can ask for an instance that implements the IOrderRepository interface like this:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;"><span
style="color:#2b91af;">IOrderRepository</span> repository = <span
style="color:#2b91af;">Container</span>.Resolve&lt;<span
style="color:#2b91af;">IOrderRepository</span>&gt;();</p></div><p>So now our client is completely decoupled from the implementation of IOrderRepository, as well as the dependencies it may or may not have.</p><p>Ok, lets suppose that this implementation makes it to the production environment.  Everything's working but for some reason, someone makes a decision to retrieve the orders from a specially prepared XML file instead of the database.  Unfortunately, your OrderDataAccessor class communicates with a SQL server database. Luckily, the OrderRepository implementation doesn't know which specific implementation of IOrderDataAccessor it's using.  We just need to make sure that every time someone needs an IOrderRepository instance, it uses the new xml-based IOrderDataAccessor implementation instead of the one we originally intended.</p><p>Because we're using Dependency Injection and an IoC container, this only requires changing one line of code:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponent&lt;<span
style="color:#2b91af;">IOrderDataAccessor</span>, <span
style="color:#2b91af;">XmlOrderDataAccessor</span>&gt;();</p></div><p>Actually, if we'd put the mapping between the IOrderDataAccessor type and the XmlOrderDataAccessor implementation in an xml file, we wouldn't even have to change any code! Well, except for the XmlOrderDataAccessor implementation obviously.</p><p>We can even take this one step further... After the change to the xml-based OrderDataAccessor went successfully, they (the 'business') all of a sudden want to log who retrieves or saves each order for auditing purposes.</p><p>Hmmm, alright then... We create an implementation of IOrderRepository which keeps extensive auditing logs so they can be retrieved later on. We could just inherit from the default OrderRepository implementation and add auditing logic before each method is executed.  Then we'd only have to configure our IoC container to return a different instance of the IOrderRepository type whenever someone requests it:</p><div
style="font-family:Consolas;font-size:10pt;color:black;background:white;"><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color:blue;">static</span> Container()</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container = <span
style="color:blue;">new</span> <span
style="color:#2b91af;">WindsorContainer</span>();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponent&lt;<span
style="color:#2b91af;">IOrderDataAccessor</span>, <span
style="color:#2b91af;">XmlOrderDataAccessor</span>&gt;();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _container.AddComponent&lt;<span
style="color:#2b91af;">IOrderRepository</span>, <span
style="color:#2b91af;">OrderRepositoryWithAuditing</span>&gt;();</p><p
style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p>Again, our client code does not need to be modified in any way, yet we did modify the runtime behavior of the application.  Instead of retrieving the Orders from a SQL database, it's now retrieving them from an XML file, and the repository is performing auditing as well, without having to change any client code.</p><p>And if we were using the xml-configuration features of Windsor, we could get all of this working without even having to recompile the client-assemblies.</p><p>This was just an introduction to using an IoC contianer (Castle's Windsor specifically) and we briefly touched on benefits that you can achieve with this way of working.  The Windsor container can do much more, but you'll either have to figure that stuff out yourself, or wait for future posts about its other features/possibilities <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F04%2Fintroduction-to-ioc-with-windsor%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/04/introduction-to-ioc-with-windsor/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/04/introduction-to-ioc-with-windsor/"  data-text="Introduction to IoC with Windsor" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/04/introduction-to-ioc-with-windsor/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/04/introduction-to-ioc-with-windsor/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/04/introduction-to-ioc-with-windsor/feed/</wfw:commentRss> <slash:comments>6</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Database Caching 2/57 queries in 0.037 seconds using disk: basic
Object Caching 1150/1262 objects using disk: basic
Content Delivery Network via Amazon Web Services: CloudFront: d18sni7re4ly7f.cloudfront.net

Served from: davybrion.com @ 2012-05-23 13:45:38 -->
