<?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; Aspect Oriented Programming</title>
	<atom:link href="http://davybrion.com/blog/category/aspect-oriented-programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://davybrion.com/blog</link>
	<description>Trying to walk that thin line between intelligence and ignorance</description>
	<lastBuildDate>Thu, 29 Jul 2010 20:51:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<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&#8217;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&#8217;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&#8217;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&#8217;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&#8217;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&#8217;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&#8217;t even know about the circuit breaker.  I also don&#8217;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&#8217;re going to use Castle Windsor&#8217;s Interceptors to make this work.  First, the implementation of the CircuitBreaker class:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">class</span> <span class="cb2">CircuitBreaker</span> : <span class="cb2">IInterceptor</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">readonly</span> <span class="cb1">object</span> monitor = <span class="cb1">new</span> <span class="cb1">object</span>();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb2">CircuitBreakerState</span> state;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">int</span> failures;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">int</span> threshold;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb2">TimeSpan</span> timeout;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> CircuitBreaker(<span class="cb1">int</span> threshold, <span class="cb2">TimeSpan</span> timeout)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">this</span>.threshold = threshold;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">this</span>.timeout = timeout;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; MoveToClosedState();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">void</span> Intercept(<span class="cb2">IInvocation</span> invocation)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">using</span> (<span class="cb2">TimedLock</span>.Lock(monitor))</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; state.ProtectedCodeIsAboutToBeCalled();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">try</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; invocation.Proceed();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">catch</span> (<span class="cb2">Exception</span> e)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">using</span> (<span class="cb2">TimedLock</span>.Lock(monitor))</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; failures++;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; state.ActUponException(e);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">throw</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">using</span> (<span class="cb2">TimedLock</span>.Lock(monitor))</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; state.ProtectedCodeHasBeenCalled();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">void</span> MoveToClosedState()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; state = <span class="cb1">new</span> <span class="cb2">ClosedState</span>(<span class="cb1">this</span>);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">void</span> MoveToOpenState()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; state = <span class="cb1">new</span> <span class="cb2">OpenState</span>(<span class="cb1">this</span>);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">void</span> MoveToHalfOpenState()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; state = <span class="cb1">new</span> <span class="cb2">HalfOpenState</span>(<span class="cb1">this</span>);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">void</span> ResetFailureCount()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; failures = 0;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">bool</span> ThresholdReached()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> failures &gt;= threshold;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">abstract</span> <span class="cb1">class</span> <span class="cb2">CircuitBreakerState</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">protected</span> <span class="cb1">readonly</span> <span class="cb2">CircuitBreaker</span> circuitBreaker;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">protected</span> CircuitBreakerState(<span class="cb2">CircuitBreaker</span> circuitBreaker)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">this</span>.circuitBreaker = circuitBreaker;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb1">void</span> ProtectedCodeIsAboutToBeCalled() { }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb1">void</span> ProtectedCodeHasBeenCalled() { }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb1">void</span> ActUponException(<span class="cb2">Exception</span> e) { }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">class</span> <span class="cb2">ClosedState</span> : <span class="cb2">CircuitBreakerState</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> ClosedState(<span class="cb2">CircuitBreaker</span> circuitBreaker)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; : <span class="cb1">base</span>(circuitBreaker)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; circuitBreaker.ResetFailureCount();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">override</span> <span class="cb1">void</span> ActUponException(<span class="cb2">Exception</span> e)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (circuitBreaker.ThresholdReached()) circuitBreaker.MoveToOpenState();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">class</span> <span class="cb2">OpenState</span> : <span class="cb2">CircuitBreakerState</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">readonly</span> <span class="cb2">Timer</span> timer;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> OpenState(<span class="cb2">CircuitBreaker</span> circuitBreaker)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; : <span class="cb1">base</span>(circuitBreaker)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; timer = <span class="cb1">new</span> <span class="cb2">Timer</span>(circuitBreaker.timeout.TotalMilliseconds);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; timer.Elapsed += TimeoutHasBeenReached;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; timer.AutoReset = <span class="cb1">false</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; timer.Start();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">void</span> TimeoutHasBeenReached(<span class="cb1">object</span> sender, <span class="cb2">ElapsedEventArgs</span> e)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; circuitBreaker.MoveToHalfOpenState();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">override</span> <span class="cb1">void</span> ProtectedCodeIsAboutToBeCalled()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">throw</span> <span class="cb1">new</span> <span class="cb2">OpenCircuitException</span>();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">class</span> <span class="cb2">HalfOpenState</span> : <span class="cb2">CircuitBreakerState</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> HalfOpenState(<span class="cb2">CircuitBreaker</span> circuitBreaker) : <span class="cb1">base</span>(circuitBreaker) { }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">override</span> <span class="cb1">void</span> ActUponException(<span class="cb2">Exception</span> e)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; circuitBreaker.MoveToOpenState();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">override</span> <span class="cb1">void</span> ProtectedCodeHasBeenCalled()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; circuitBreaker.MoveToClosedState();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Notice how the CircuitBreaker class implements Windsor&#8217;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>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: #2b91af; }
.cb2 { color: #a31515; }
.cb3 { color: blue; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; container.Register(<span class="cb1">Component</span>.For&lt;<span class="cb1">CircuitBreaker</span>&gt;().LifeStyle.Singleton</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp; .Named(<span class="cb2">&quot;serviceProxyCircuitBreaker&quot;</span>)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp; .DependsOn(<span class="cb3">new</span> <span class="cb1">Hashtable</span> { { <span class="cb2">&quot;threshold&quot;</span>, 5 }, { <span class="cb2">&quot;timeout&quot;</span>, <span class="cb1">TimeSpan</span>.FromMinutes(5) } }));</p>
</div>
<p></code></p>
<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>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: #2b91af; }
.cb2 { color: #a31515; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; container.Register(<span class="cb1">Component</span>.For&lt;<span class="cb1">IServiceProxy</span>&gt;().ImplementedBy&lt;<span class="cb1">ServiceProxy</span>&gt;().LifeStyle.Transient</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .Interceptors(<span class="cb1">InterceptorReference</span>.ForKey(<span class="cb2">&quot;serviceProxyCircuitBreaker&quot;</span>)).Anywhere);</p>
</div>
<p></code></p>
<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>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/07/protecting-your-application-from-remote-problems/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>WCF Exception Handling with PostSharp</title>
		<link>http://davybrion.com/blog/2008/05/wcf-exception-handling-with-postsharp/</link>
		<comments>http://davybrion.com/blog/2008/05/wcf-exception-handling-with-postsharp/#comments</comments>
		<pubDate>Fri, 23 May 2008 09:37:55 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Aspect Oriented Programming]]></category>
		<category><![CDATA[PostSharp]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=120</guid>
		<description><![CDATA[In your WCF service methods, you should always provide proper exception handling. The exception handling code is almost always the same, so it&#8217;s usually just copy/pasted in each method. Here&#8217;s an example of a typical service method: &#160;&#160;&#160; &#160;&#160;&#160; public void PersistOrder(Order order) &#160;&#160;&#160; &#160;&#160;&#160; { &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; try &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; { &#160;&#160;&#160; [...]]]></description>
			<content:encoded><![CDATA[<p>In your WCF service methods, you should always provide proper exception handling. The exception handling code is almost always the same, so it&#8217;s usually just copy/pasted in each method. Here&#8217;s an example of a typical service method:</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> <span style="color: blue;">void</span> PersistOrder(<span style="color: #2b91af;">Order</span> order)</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;">try</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</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;">IPersistOrderHandler</span>&gt;().Handle(order);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">catch</span> (<span style="color: #2b91af;">BusinessException</span> b)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">throw</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">FaultException</span>&lt;<span style="color: #2b91af;">BusinessExceptionInformation</span>&gt;(<span style="color: blue;">new</span> <span style="color: #2b91af;">BusinessExceptionInformation</span>(b), </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">new</span> <span style="color: #2b91af;">FaultReason</span>(b.Message));&nbsp;&nbsp; </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">catch</span> (<span style="color: #2b91af;">FaultException</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">throw</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">catch</span> (<span style="color: #2b91af;">Exception</span> e)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</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;">ILogger</span>&gt;().LogException(e);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">throw</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">FaultException</span>(<span style="color: blue;">new</span> <span style="color: #2b91af;">FaultReason</span>(e.Message));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>That&#8217;s a lot of code, even though only ONE line will differ from the other service methods in this service.  Let&#8217;s clean up this mess, shall we? Exception handling is a <a href="http://en.wikipedia.org/wiki/Cross-cutting_concern">cross cutting concern</a> so we might as well put it in one place (at least, one place for each different kind of exception handling that you need).  We&#8217;ll use PostSharp to define an ApplyServiceExceptionHandling aspect:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">Serializable</span>]</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">ApplyServiceExceptionHandling</span> : <span style="color: #2b91af;">OnExceptionAspect</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> OnException(<span style="color: #2b91af;">MethodExecutionEventArgs</span> eventArgs)</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;">if</span> (eventArgs.Exception <span style="color: blue;">is</span> <span style="color: #2b91af;">BusinessException</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">throw</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">FaultException</span>&lt;<span style="color: #2b91af;">BusinessExceptionInformation</span>&gt;(</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">new</span> <span style="color: #2b91af;">BusinessExceptionInformation</span>(eventArgs.Exception <span style="color: blue;">as</span> <span style="color: #2b91af;">BusinessException</span>),</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">new</span> <span style="color: #2b91af;">FaultReason</span>(eventArgs.Exception.Message));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">else</span> <span style="color: blue;">if</span> (eventArgs.Exception <span style="color: blue;">is</span> <span style="color: #2b91af;">FaultException</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; eventArgs.FlowBehavior = <span style="color: #2b91af;">FlowBehavior</span>.RethrowException;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">else</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</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;">ILogger</span>&gt;().LogException(eventArgs.Exception);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">throw</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">FaultException</span>(<span style="color: blue;">new</span> <span style="color: #2b91af;">FaultReason</span>(eventArgs.Exception.Message));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>And now we can modify the earlier service method to 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: #2b91af;">ApplyServiceExceptionHandling</span>]</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> PersistOrder(<span style="color: #2b91af;">Order</span> order)</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: #2b91af;">Container</span>.Resolve&lt;<span style="color: #2b91af;">IPersistOrderHandler</span>&gt;().Handle(order);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>That&#8217;s a lot cleaner than the previous version right? Actually, this service has more than one service method so we&#8217;re better off moving the ApplyServiceExceptionHandling attribute to the class level instead of the method level:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">ApplyServiceExceptionHandling</span>]</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">OrderManagementService</span> : <span style="color: #2b91af;">IOrderManagementService</span></p>
</div>
<p></code></p>
<p>now we can get rid of all of the exception handling code in each service method, but each one will have exception handling applied to it because the exception handling aspect is applied to the class, and thus, to each method of that class.  And if you need to modify your exception handling (to handle TargetInvocationExceptions with BusinessExceptions as InnerExceptions for instance?) you&#8217;d only have to do this in one place.</p>
<p>Btw, i&#8217;m aware of WCF&#8217;s IErrorHandler interface (which allows you to handle exceptions in a general manner as well)&#8230; i just don&#8217;t like it <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/05/wcf-exception-handling-with-postsharp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Adding Behavior With PostSharp</title>
		<link>http://davybrion.com/blog/2008/05/adding-behavior-with-postsharp/</link>
		<comments>http://davybrion.com/blog/2008/05/adding-behavior-with-postsharp/#comments</comments>
		<pubDate>Wed, 21 May 2008 20:12:41 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Aspect Oriented Programming]]></category>
		<category><![CDATA[PostSharp]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=118</guid>
		<description><![CDATA[A little while ago, i talked about adding behavior to components using Windsor&#8217;s Interceptors. I wanted to try something similar with PostSharp, which is a very powerful Aspect Oriented Programming framework for the .NET world. Discussing everything PostSharp can do (which is a lot) is way beyond the scope of this post, so we&#8217;ll just [...]]]></description>
			<content:encoded><![CDATA[<p>A little while ago, i talked about <a href="http://davybrion.com/blog/2008/05/adding-behavior-without-modifying-existing-code-with-windsor/">adding behavior to components using Windsor&#8217;s Interceptors</a>.  I wanted to try something similar with <a href="http://www.postsharp.org/">PostSharp</a>, which is a very powerful <a href="http://en.wikipedia.org/wiki/Aspect-Oriented_Programming">Aspect Oriented Programming</a> framework for the .NET world.  Discussing everything PostSharp can do (which is <strong>a lot</strong>) is way beyond the scope of this post, so we&#8217;ll just focus on what i&#8217;m trying to do, and how PostSharp helps us with that. </p>
<p>In the previous post, i used a logging example&#8230; i didn&#8217;t want logging code mixed up with my real code, so i used a Windsor Interceptor to intercept calls to classes that i had configured to be logged.  The interceptor would then log before and after the method calls were executed.  In this post we&#8217;ll do something very similar, but a bit more advanced.  We&#8217;re gonna write some tracing logic that will write a trace statement when the method is entered, along with the parameter values for each of its parameters.  Then after the original method has executed, we&#8217;ll write a trace statement to indicate that we have left the method, and we&#8217;ll display the return value of the method as well, if there is one. That kind of tracing information can be very valuable, but writing that code is extremely tedious work.  Nobody wants to do that, right? I sure as hell don&#8217;t.</p>
<p>We&#8217;ll use the following simple class as an example:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Calculator</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">int</span> Add(<span style="color: blue;">int</span> firstValue, <span style="color: blue;">int</span> secondValue)</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;">return</span> firstValue + secondValue;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">int</span> Subtract(<span style="color: blue;">int</span> firstValue, <span style="color: blue;">int</span> secondValue)</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;">return</span> firstValue - secondValue;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>This calculator has a pretty limited feature-set, but we don&#8217;t need anything more for this example. Ok, so how do we add the tracing code without actually adding it to this code? We can just compile the code, and then we can have PostSharp inject some extra code to the compiled code.  Sounds pretty hard, right? It is. But PostSharp Laos is a small framework that runs on top of PostSharp and it takes care of the hard work for you.  PostSharp Laos offers some base classes which make it really easy for you to write your aspects (if you don&#8217;t understand that term, you should have clicked on the aspect oriented programming link earlier in the post <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).  There are a couple of approaches you can choose between, and they all have their pro&#8217;s and con&#8217;s.  A nice overview of the different kinds of aspects you can inherit from can be found <a href="http://doc.postsharp.org/1.0/UserGuide/Laos/AspectKinds/Overview.html">here</a>.  For this example, we&#8217;ll use the OnMethodInvocationAspect base class. This basically intercepts calls to methods and allows you to add some logic. </p>
<p>So what would our tracing aspect look like? How about this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">Serializable</span>]</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">TraceAspect</span> : <span style="color: #2b91af;">OnMethodInvocationAspect</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> OnInvocation(<span style="color: #2b91af;">MethodInvocationEventArgs</span> eventArgs)</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;">string</span> methodName = GetFullMethodName(eventArgs);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; WriteOutput(<span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">"Entering {0}"</span>, methodName));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; WriteParameterInfo(eventArgs.Delegate.Method.GetParameters(), eventArgs.GetArgumentArray());</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">base</span>.OnInvocation(eventArgs); <span style="color: green;">// calls the original method</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; WriteOutput(<span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">"Leaving {0}"</span>, methodName));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; WriteReturnValueInfo(eventArgs.Delegate.Method.ReturnType, eventArgs.ReturnValue);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">void</span> WriteParameterInfo(<span style="color: #2b91af;">ParameterInfo</span>[] parameterInfos, <span style="color: blue;">object</span>[] parameters)</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;">if</span> (parameterInfos == <span style="color: blue;">null</span> || parameterInfos.Length == 0)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; WriteOutput(<span style="color: #a31515;">"With the following parameters: "</span>);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&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; parameterInfos.Length; i++)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; WriteOutput(<span style="color: blue;">string</span>.Format(<span style="color: #a31515;">"{0} = {1}"</span>, parameterInfos[i].Name, parameters[i]));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">void</span> WriteReturnValueInfo(<span style="color: #2b91af;">Type</span> returnType, <span style="color: blue;">object</span> returnValue)</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;">if</span> (returnType == <span style="color: blue;">typeof</span>(<span style="color: blue;">void</span>))</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; WriteOutput(<span style="color: blue;">string</span>.Format(<span style="color: #a31515;">"Return Value: {0}"</span>, returnValue));&nbsp;&nbsp;&nbsp; </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">string</span> GetFullMethodName(<span style="color: #2b91af;">MethodInvocationEventArgs</span> args)</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;">return</span> args.Delegate.Target.GetType().FullName + <span style="color: #a31515;">"."</span> + args.Delegate.Method.Name;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">void</span> WriteOutput(<span style="color: blue;">string</span> line)</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: #2b91af;">Trace</span>.WriteLine(<span style="color: #2b91af;">DateTime</span>.Now.TimeOfDay + <span style="color: #a31515;">" "</span> + line);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>So now we have a trace aspect which shows some valuable information about method calls&#8230; it shows when the method is entered, which parameters were passed in, when we leave the method and what the return value is.  </p>
<p>So how do we apply this aspect to our code? We modify the definition of the Calculator class 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; [<span style="color: #2b91af;">TraceAspect</span>]</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Calculator</span></p>
</div>
<p></code></p>
<p>And then we compile&#8230; Well actually you have to add something to your project file so PostSharp can modify the compiled code, but since that&#8217;s covered nicely in the PostSharp documentation we&#8217;ll skip that step in this post.  Anyways, when you compile this, you&#8217;ll get the following build output:</p>
<p><code></p>
<p>------ Build started: Project: UsingPostSharp, Configuration: Debug Any CPU ------<br />
C:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:POSTSHARP;DEBUG;TRACE /reference:..\Libs\postsharp\PostSharp.Laos.dll /reference:..\Libs\postsharp\PostSharp.Public.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.DataSetExtensions.dll" /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll" /debug+ /debug:full /filealign:512 /optimize- /out:obj\Debug\UsingPostSharp.exe /target:exe Program.cs Properties\AssemblyInfo.cs TraceAspect.cs</p>
<p>Compile complete -- 0 errors, 0 warnings<br />
<strong>"C:\mydocs\src\dbr\Experiments\UsingPostSharp\Libs\postsharp\PostSharp.exe"  "C:\mydocs\src\dbr\Experiments\UsingPostSharp\Libs\postsharp\Default.psproj" "C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\obj\Debug\UsingPostSharp.exe" "/P:Output=obj\Debug\PostSharp\UsingPostSharp.exe " "/P:ReferenceDirectory=C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp " "/P:Configuration=Debug " "/P:Platform=AnyCPU " "/P:SearchPath=bin\Debug\, " "/P:IntermediateDirectory=obj\Debug\PostSharp " "/P:CleanIntermediate=False " "/P:MSBuildProjectFullPath=C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\UsingPostSharp.csproj " "/P:SignAssembly=False " "/P:PrivateKeyLocation= "<br />
PostSharp 1.0 [1.0.9.365] - Copyright (c) Gael Fraiteur, 2005-2008.</p>
<p>info PS0035: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ilasm.exe "C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\obj\Debug\PostSharp\UsingPostSharp.il" /QUIET /EXE /PDB "/RESOURCE=C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\obj\Debug\PostSharp\UsingPostSharp.res" "/OUTPUT=C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\obj\Debug\PostSharp\UsingPostSharp.exe" /SUBSYSTEM=3 /FLAGS=1 /BASE=4194304 /STACK=1048576 /ALIGNMENT=512 /MDV=v2.0.50727<br />
UsingPostSharp -> C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\bin\Debug\UsingPostSharp.exe</strong><br />
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========</p>
<p></code></p>
<p>If we use the calculator class 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; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> calculator = <span style="color: blue;">new</span> <span style="color: #2b91af;">Calculator</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; calculator.Add(10, 15);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; calculator.Subtract(10, 15);</p>
</div>
<p></code></p>
<p>We&#8217;ll get the following trace output:</p>
<p><code></p>
<p>21:48:49.9414848 Entering UsingPostSharp.Calculator.~Add<br />
21:48:49.9615136 With the following parameters:<br />
21:48:49.9615136 firstValue = 10<br />
21:48:49.9615136 secondValue = 15<br />
21:48:49.9615136 Leaving UsingPostSharp.Calculator.~Add<br />
21:48:49.9615136 Return Value: 25<br />
21:48:49.9615136 Entering UsingPostSharp.Calculator.~Subtract<br />
21:48:49.9615136 With the following parameters:<br />
21:48:49.9615136 firstValue = 10<br />
21:48:49.9615136 secondValue = 15<br />
21:48:49.9615136 Leaving UsingPostSharp.Calculator.~Subtract<br />
21:48:49.9615136 Return Value: -5</p>
<p></code></p>
<p>How nice is that? With some exception handling, better formatting and some clever indenting, this tracing aspect could be the only tracing code you&#8217;ll ever need from now on <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So how does it work? Well, we can look at the compiled code in reflector for that.  Here&#8217;s how the Add method looks like after PostSharp modified the code:</p>
<p><code></p>
<p>    private int ~Add(int firstValue, int secondValue)<br />
    {<br />
        return (firstValue + secondValue);<br />
    }</p>
<p>    [DebuggerNonUserCode, CompilerGenerated]<br />
    public int Add(int firstValue, int secondValue)<br />
    {<br />
        Delegate delegateInstance = new ~PostSharp~Laos~Implementation.~delegate~0(this.~Add);<br />
        object[] arguments = new object[] { firstValue, secondValue };<br />
        MethodInvocationEventArgs eventArgs = new MethodInvocationEventArgs(delegateInstance, arguments);<br />
        ~PostSharp~Laos~Implementation.TraceAspect~1.OnInvocation(eventArgs);<br />
        return (int) eventArgs.ReturnValue;<br />
    }</p>
<p></code></p>
<p>As you can see, it&#8217;s renamed our Add method to ~Add, and it added another Add method which calls the OnInvocation method of our TraceAspect class with the correct MethodInvocationEventArgs.  Pretty cool stuff IMO.  Oh and btw, if you&#8217;re debugging this code in Visual Studio, you still only see your own code, with the original method name.  While you step through it, the code runs just like it normally would, and the applied aspects are also executed. Very impressive.</p>
<p>If you use the OnMethodBoundaryAspect instead of the OnMethodInvocationAspect, you&#8217;ll see that the modified code doesn&#8217;t replace your method like it did here.  But it will add a lot of extra code to it as well.  All in all, there are a lot of possibilities here.  If i&#8217;m not mistaken, i can now even use our TraceAspect and use it on classes in other assemblies, even if i don&#8217;t have access to them.  We&#8217;ll look into that in a future post <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Anyway, PostSharp is an extremely impressive piece of software which provides a whole lot of power and flexibility. You should definitely check it out and play around with it&#8230; i know i&#8217;m gonna be experimenting with it more often to see what kind of weird and cool stuff we can make it do <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/05/adding-behavior-with-postsharp/feed/</wfw:commentRss>
		<slash:comments>7</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&#8217;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&#8217;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&#8217;s logging code all over the OrderRepository class and in most cases, it&#8217;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&#8217;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&#8230; 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;">&#8220;.&#8221;</span> + invocation.GetConcreteMethod().Name;</p>
<p style="margin:0;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Log(<span style="color:#a31515;">&#8220;Entering method: &#8220;</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;">&#8220;Leaving mehod: &#8220;</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;">&#8221; &#8220;</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>&#8220;<span style="color:blue;">ILogger</span>&#8220;<span style="color:blue;"> </span><span style="color:red;">service</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">Components.ILogger, Components</span>&#8220;<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>&#8220;<span style="color:blue;">Components.Logger, Components</span>&#8220;<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>&#8220;<span style="color:blue;">LoggingInterceptor</span>&#8220;<span style="color:blue;"> </span><span style="color:red;">service</span><span style="color:blue;">=</span>&#8220;<span style="color:blue;">Components.LoggingInterceptor, Components</span>&#8220;</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>&#8220;<span style="color:blue;">Components.LoggingInterceptor, Components</span>&#8220;</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>&#8220;<span style="color:blue;">transient</span>&#8220;<span style="color:blue;"> /&gt;</span></p>
</div>
<p>Right&#8230; 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>&#8220;<span style="color:blue;">IOrderRepository</span>&#8220;</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>&#8220;<span style="color:blue;">Components.IOrderRepository, Components</span>&#8220;</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>&#8220;<span style="color:blue;">Components.OrderRepository, Components</span>&#8220;<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&#8217;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>
<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>And we didn&#8217;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>
]]></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>
	</channel>
</rss>
