<?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; Dependency Injection</title> <atom:link href="http://davybrion.com/blog/category/dependency-injection/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>Sun, 29 Jan 2012 10:48:12 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>Why You Don&#8217;t Need Dependency Injection In Ruby</title><link>http://davybrion.com/blog/2010/10/why-you-dont-need-dependency-injection-in-ruby/</link> <comments>http://davybrion.com/blog/2010/10/why-you-dont-need-dependency-injection-in-ruby/#comments</comments> <pubDate>Mon, 11 Oct 2010 06:00:32 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Opinions]]></category> <category><![CDATA[Ruby]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2768</guid> <description><![CDATA[If you're new to Ruby and you're coming from static languages like C# or Java, you'll probably wonder why there isn't much interest in Dependency Injection in the Ruby community. The answer is quite simple: because you don't need it. Now, that's not to say that Dependency Injection isn't a valuable technique in your toolbox. [...]]]></description> <content:encoded><![CDATA[<p>If you're new to Ruby and you're coming from static languages like C# or Java, you'll probably wonder why there isn't much interest in Dependency Injection in the Ruby community.  The answer is quite simple: because you don't need it.  Now, that's not to say that Dependency Injection isn't a valuable technique in your toolbox.  In fact, if you're doing C# or Java i'd even go as far as saying it's absolutely necessary to use Dependency Injection in most of your code.  Two of the biggest reasons (i know there are more, but let's focus on these for now) why Dependency Injection is important if you're using a static language are these:</p><ol><li>Highly increased testability because you can control the dependencies during automated tests</li><li>Lowered coupling between classes which enables you to change implementations of dependencies at will (granted, not a lot of people actually do that often but it certainly is <a
href="http://davybrion.com/blog/2009/12/real-world-benefits-from-loose-coupling-inversion-of-control-and-dependency-injection/">a real benefit</a>)</li></ol><p>In Ruby however, you don't really need dependency injection to achieve the 2 benefits mentioned above as i hope the following contrived example shows.  Suppose we have the following 2 classes.</p><div><pre class="brush: ruby; title: ; notranslate">
class Dependency
  def do_something_with(some_object)
    p some_object
  end
end

class SomeClass
  def work_your_magic_on(something)
    Dependency.new.do_something_with something
  end
end
</pre></div><p>This is no good. The work_your_magic_on method from SomeClass directly instantiates a new instance of the Dependency class.  During automated tests, we could actually replace the implementation of the new method of the Dependency class to return a stub or a mock if we want to instead of an instance of the real thing.  But we could never easily change the implementation of the dependency that SomeClass requires to function properly in real production code without screwing up everything else that also happens to depend on the Dependency class.</p><p>If you're coming from a static language, you'd probably be inclined to change SomeClass to this:</p><div><pre class="brush: ruby; title: ; notranslate">
class SomeClass
  def initialize(dependency)
    @dependency = dependency
  end
  
  def work_your_magic_on(something)
    @dependency.do_something_with something
  end
end
</pre></div><p>Ahh, that's much better.  The dependency is now injected in SomeClass' initializer method and we can very easily achieve the above mentioned 2 benefits by passing whatever we want to each instance of SomeClass, as long as it has a do_something_with method.  The biggest downside however is that every consumer of SomeClass instances now needs to know about the dependencies that it requires to function properly.  This quickly becomes very painful because using Dependency Injection throughout your codebase will very quickly lead to having to satisfy the dependencies of the dependencies of the dependencies of the dependencies of the class you actually need to use.  This quickly requires the usage of a good Inversion Of Control Container to handle all of these dependencies for you.  There's just one problem: there doesn't seem to be a widely used IOC Container in Ruby.  Which in itself tells you that it's simply not needed in Ruby.</p><p>There's a better way to modify SomeClass:</p><div><pre class="brush: ruby; title: ; notranslate">
class SomeClass
  def work_your_magic_on(something)
    get_dependency.do_something_with something
  end
  
  private
  
  def get_dependency
    @dependency = Dependency.new if @dependency.nil?
    @dependency
  end
end
</pre></div><p>Now, the ALT.NET fanbois will still tell you how wrong this is because SomeClass still has a direct dependency on the Dependency class.  I should know because i was one of them.  And again, in C# or Java i'd definitely agree that this code is bad.  Not so in Ruby however because i can easily replace the actual implementation of SomeClass' dependency in both automated tests and actual production code, without impacting anything else that uses the Dependency class.</p><p>Suppose we have the following test:</p><div><pre class="brush: ruby; title: ; notranslate">
  def test_magic
    object = SomeClass.new
    object.work_your_magic_on &quot;some important string&quot;
    # TODO: assert that the string was passed to the dependency correctly
  end
</pre></div><p>Since i don't provide the dependency to the object that i'm testing, i can't really verify that the dependency was used correctly. I'm also not using any mocking framework since i want to show how the language itself takes away the need to inject your dependencies.  Given the following spy class:</p><div><pre class="brush: ruby; title: ; notranslate">
class DependencySpy
  @@passed_in_objects = []
  
  def self.passed_in_objects
    @@passed_in_objects
  end
  
  def do_something_with(some_object)
    @@passed_in_objects &lt;&lt; some_object
  end
end
</pre></div><p>I could now write my test like this:</p><div><pre class="brush: ruby; title: ; notranslate">
  def test_magic
    object = SomeClass.new
    def object.get_dependency
      DependencySpy.new
    end
    object.work_your_magic_on &quot;some important string&quot;
    assert DependencySpy.passed_in_objects.include? &quot;some important string&quot;
  end
</pre></div><p>And it'll pass.  The 'trick' is that i simply change the implementation of the get_dependency method for <em>the instance that i have</em>.  This doesn't change anything at the class level, merely at the instance level.  Technically, i don't really change the implementation of get_dependency in SomeClass, i merely insert a method in this particular instance which will precede the one in SomeClass during Ruby's method lookup procedure.</p><p>Also, i would like to point out that this kind of testing isn't exactly something that i'd encourage you to do, though this technique can be useful if you really need to do interaction testing.  But it's a good illustration of why you don't really need to do Dependency Injection in Ruby to write testable code.</p><p>Now you might be wondering, what's the difference between doing something like this and using a tool like TypeMock in .NET to basically achieve the same thing?  Well, when writing code like this in C# and testing it with TypeMock, you achieve one of the benefits that you could have with using Dependency Injection: being able to control the dependencies.  But you can't change the implementation of the dependency at runtime in normal production code.  In Ruby, with the approach outlined above, i can still easily achieve that like this:</p><div><pre class="brush: ruby; title: ; notranslate">
class SomeClass
  
  private
  
  def get_dependency
    @dependency = SomeOtherDependency.new if @dependency.nil?
    @dependency
  end
  
end
</pre></div><p>If this code is executed after the earlier definition of SomeClass, it will reopen SomeClass and change the implementation of the get_dependency method for each instance that will be created.  This effectively gives you the ability to change the implementation of a dependency at runtime in production code, without having to use Dependency Injection.  Now, some Dependency Injection purists will still claim that this approach is bad because SomeClass knows which implementation of the dependency it uses.  And my question to those people is: so what? I can easily change it in any situation i'd run into.  You can also consider the presence of the actual type of the dependency as the default implementation to use, without having to force the requirement of this knowledge on consumers.</p><p>There is still one situation where i would probably use Dependency Injection in Ruby though, and that is when you want to benefit from what i consider to be yet another great reason to use Dependency Injection in static languages:</p><ul><li>Not having to know anything about the lifecycle of your dependencies</li></ul><p>In this case, it's probably much easier to just inject a long-living dependency in an object with a shorter lifecycle.  However, if the dependency is basically a singleton (which is still the default for many of the .NET IOC Containers), then i actually would consider implementing the singleton as a class with nothing but class methods (similar to static methods in static languages, but not quite since you can still change them whenever you want) and having my other classes that depend on it call those methods directly, or through helper methods that i can still change when i need to.</p><p>I'm sure many people will disagree with some of the points i try to make in this post, but until i get some actual real-world reasons that invalidate my points, i simply don't see the point in sticking to a set of rules and guidelines that were largely made up out of necessity to deal with shortcomings of static languages.  That's not to say that dynamic languages don't have any shortcomings or drawbacks, but it does mean that the rules and guidelines of how to write good code are, well, simply different.  And as such, it wouldn't be wise to blindly stick with rules that were made for a different way of programming.  Question what you already know, because it might not be relevant to what you need to do <em>now</em>.</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%2F10%2Fwhy-you-dont-need-dependency-injection-in-ruby%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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/10/why-you-dont-need-dependency-injection-in-ruby/"></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/10/why-you-dont-need-dependency-injection-in-ruby/"  data-text="Why You Don&#8217;t Need Dependency Injection In Ruby" data-count="horizontal" data-via="davybrion">Tweet</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/10/why-you-dont-need-dependency-injection-in-ruby/" 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/10/why-you-dont-need-dependency-injection-in-ruby/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/10/why-you-dont-need-dependency-injection-in-ruby/feed/</wfw:commentRss> <slash:comments>24</slash:comments> </item> <item><title>Inversion Of Control Containers And Factories Aren&#8217;t Mutually Exclusive</title><link>http://davybrion.com/blog/2010/01/inversion-of-control-containers-and-factories-arent-mutually-exclusive/</link> <comments>http://davybrion.com/blog/2010/01/inversion-of-control-containers-and-factories-arent-mutually-exclusive/#comments</comments> <pubDate>Sat, 23 Jan 2010 15:14:45 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Inversion Of Control]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2224</guid> <description><![CDATA[Julian Birch recently posted a reaction to my reaction to Uncle Bob’s IOC lunacy post.&#160; Julian mistakenly thinks that i have a problem with using factories.&#160; I definitely don’t have a problem with using factories.&#160; I just have a problem with using them in the manner that Uncle Bob suggested in his post.&#160; Jeffrey Palermo [...]]]></description> <content:encoded><![CDATA[<p>Julian Birch recently posted a <a
href="http://www.colourcoding.net/Blog/archive/2010/01/19/dependency-reversi.aspx" target="_blank">reaction</a> to <a
href="http://davybrion.com/blog/2010/01/dependency-injection-inversion-rejection/" target="_blank">my reaction to Uncle Bob’s IOC lunacy post</a>.&#160; Julian mistakenly thinks that i have a problem with using factories.&#160; I definitely don’t have a problem with using factories.&#160; I just have a problem with using them in the manner that Uncle Bob suggested in his post.&#160; Jeffrey Palermo also recently posted <a
href="http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/" target="_blank">an example</a> of where he thinks using a factory is better than injecting dependencies.&#160; I wanted to react to both those posts with a real-world example of where i prefer to use a factory and how i use an IOC container to do so.</p><p>As you probably know by now, i’m a big proponent of using IOC containers.&#160; I’ve never stated that they should be used in every single application, but using one certainly pays off in most applications, especially as complexity increases gradually.&#160; When you use an IOC container, you’ll have much less need for factories.&#160;&#160; There are however two situations where i certainly prefer to use a factory.&#160; And that is when:</p><ol><li>a certain dependency might not always be used by a class <em>and</em> that dependency is expensive to create</li><li>i might need multiple instances of a dependency during the lifetime of a class</li></ol><p>A good example of both those situations is when using <a
href="http://code.google.com/p/agatha-rrsl/" target="_blank">Agatha</a>’s AsyncRequestDispatcher class from a Silverlight user control.&#160; Creating an AsyncRequestDispatcher is expensive because it in turn requires an instance of the AsyncRequestProcessorProxy class.&#160; The AsyncRequestProcessorProxy class inherits from WCF’s ClientBase class, and those types are relatively expensive to create.&#160;&#160; And due to the asynchronous nature of those service calls, you can never deterministically dispose of a AsyncRequestDispatcher instance with absolute certainty that it won’t be disposed <em>before</em> the response of the service call is returned from the service.&#160; Because of that, the AsyncRequestDispatcher class was designed to dispose of itself automatically once the response is returned.&#160; This effectively means that you’ll need a new instance of AsyncRequestDispatcher whenever you need to make an asynchronous call to an Agatha service.&#160;</p><p>For most user controls, it obviously doesn’t make sense to inject one instance of the AsyncRequestDispatcher into the user control because you often need to make multiple service calls depending on user interactions or other events.&#160;&#160; A good way to deal with this is obviously to ask a factory to create the AsyncRequestDispatcher whenever you need one.&#160;&#160; Which is why Agatha offers the AsyncRequestDispatcherFactory class, which looks like this:</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">IAsyncRequestDispatcherFactory</span></p><p
style="margin: 0px">&#160;&#160;&#160; {</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">IAsyncRequestDispatcher</span> CreateAsyncRequestDispatcher();</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">AsyncRequestDispatcherFactory</span> : <span
style="color: #2b91af">IAsyncRequestDispatcherFactory</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">IAsyncRequestDispatcher</span> CreateAsyncRequestDispatcher()</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">return</span> <span
style="color: #2b91af">IoC</span>.Container.Resolve&lt;<span
style="color: #2b91af">IAsyncRequestDispatcher</span>&gt;();</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>Now, some of you are probably thinking: what is the difference between this and Uncle Bob’s example?&#160; Well, unlike Uncle Bob’s example this factory is not responsible for registering the required components to create an AsyncRequestDispatcher with the container.&#160; It merely resolves an instance and returns it.&#160; And yes, it uses the container to do so.&#160;&#160; I could actually just new up an AsyncRequestDispatcher myself but then the factory would also have to <em>know</em> about its dependencies and make sure it’d be able to create them.&#160; If those dependencies have dependencies of their own, i’m back to dealing with dependencies manually which is exactly what i’m trying to avoid throughout my codebase.</p><p>I can’t come up with a single reason why this would be wrong, but some of you probably will so feel free to point out those reasons <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><p>The benefit of this factory is that it enables me to delay the instantiation of an expensive dependency, and it also enables me to get more than one instance if i need to during the lifetime of a single object.&#160; At the same time, it doesn’t have <em>any</em> of the downsides of Uncle Bob’s approach.&#160; Also, this approach is something that you won’t need to resort to throughout your codebase, it’s more for edge-cases.</p><p>Now, how do we use this factory?&#160; Instead of new’ing the factory manually like Jeffrey does in his example, the factory is registered with the IOC container and i simply inject the factory into the class that needs to use it.&#160; This still enables me to change implementations of both the factory as well as the instances the factory needs to create.&#160; And it also makes it easy to stub or mock the factory during tests.&#160; I get all of the benefits from using Dependency Injection and an IOC container, and i have yet to notice any downsides to this approach.&#160; But again, i only use this approach in the 2 situations i mentioned in the beginning of this post.&#160; In most cases, you really don’t need factories anymore.&#160; And when you do, just leverage your IOC container to make the factory as simple and dumb as possible.</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%2F01%2Finversion-of-control-containers-and-factories-arent-mutually-exclusive%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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/01/inversion-of-control-containers-and-factories-arent-mutually-exclusive/"></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/01/inversion-of-control-containers-and-factories-arent-mutually-exclusive/"  data-text="Inversion Of Control Containers And Factories Aren&rsquo;t Mutually Exclusive" data-count="horizontal" data-via="davybrion">Tweet</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/01/inversion-of-control-containers-and-factories-arent-mutually-exclusive/" 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/01/inversion-of-control-containers-and-factories-arent-mutually-exclusive/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/01/inversion-of-control-containers-and-factories-arent-mutually-exclusive/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Dependency Injection Inversion Rejection</title><link>http://davybrion.com/blog/2010/01/dependency-injection-inversion-rejection/</link> <comments>http://davybrion.com/blog/2010/01/dependency-injection-inversion-rejection/#comments</comments> <pubDate>Tue, 19 Jan 2010 08:19:38 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Inversion Of Control]]></category><guid
isPermaLink="false">http://davybrion.com/blog/2010/01/dependency-injection-inversion-rejection/</guid> <description><![CDATA[Uncle Bob has done it again.&#160; In his latest post, he actually advises people to go back to manual dependency injection instead of relying on a framework (our beloved IOC containers) to do it for us.&#160; You really ought to check out the post and his examples in particular.&#160; Done with that? Ok. There are [...]]]></description> <content:encoded><![CDATA[<p>Uncle Bob has done it again.&#160; In <a
href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion" target="_blank">his latest post</a>, he actually advises people to go back to manual dependency injection instead of relying on a framework (our beloved IOC containers) to do it for us.&#160; You really ought to check out the post and his examples in particular.&#160; Done with that? Ok.</p><p>There are two major problems that i have with his post.&#160; The first is this one:</p><blockquote><p>I like this because now all the Guice is in one well understood place. I don’t have Guice all over my application. Rather, I’ve got factories that contain the Guice. Guicey factories that keep the Guice from being smeared all through my application.</p><p>What’s more, if I wanted to replace Guice with some other DI framework, I know exactly what classes would need to change, and how to change them. So I’ve kept Guice uncoupled from my application.</p></blockquote><p>For those of you who don’t know, Guice is an IOC container from Google.&#160; Uncle Bob doesn’t want references of an IOC container spread out throughout his application, but he doesn’t seem to mind coupling his factories with his IOC container for some reason.&#160; He seems to think that he can actually switch to a different container more easily because of this, because he would only have to modify his factories.</p><p>Here’s the deal.&#160; If you have more than a handful of references to your IOC container in your code (apart from the registration obviously), then you really don’t know what using an IOC container is all about.&#160; Yes, i know Uncle Bob is supposed to be a legend.&#160; Yes, i realize that i’m saying that a legend in the OO world doesn’t seem to grasp some of the most important concepts of using an IOC container.&#160; Can you really disagree with that after reading his post?</p><p>His whole idea of making it easier to switch to another container with his approach is ludicrous.&#160; He would have to modify every single factory that he uses, and in his trivial non-real world examples that wouldn’t be a lot to do but out here in the real world, we’d end up with a boatload of those factories and they would all have to be modified.&#160; Conversely, if you’re using an IOC container in the way it is meant to be used, you’d only have to change your registration code and the <em>one or two</em> places where you resolve something manually through the container.&#160; And that’s it.&#160; Yes, you typically only need one or two places where you use the container directly.&#160; Well, unless you’re Uncle Bob of course.</p><p>My other problem with his post is with the sample that he uses.&#160; It really is a very simplistic example and the approach he outlines simply does not scale when you’re dealing with large, real-world codebases.&#160; His approach might work for the size of the examples in his books, or for the code of <a
href="http://fitnesse.org/" target="_blank">Fitnesse</a>, but if i were to apply his recommended approach for some of the systems that we’re working on, it would lead to a terrible mess very quickly.&#160; Not exactly what i’d have in mind when thinking of <a
href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1263888825&amp;sr=8-1" target="_blank">Clean Code</a>.</p><p>The one thing i do like about this post? Well, there are quite a few people who follow Uncle Bob blindly and can’t say a single bad thing about his thoughts/ideas/approaches.&#160; I know quite a few of them make extensive use of IOC containers and some of them are even involved in the development of these containers.&#160; Hopefully, Uncle Bob’s post will finally convince these people that blindly following <em>anyone</em> is simply never a good idea and that you have to keep a critical mindset for everything that you read, no matter who wrote it.</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%2F01%2Fdependency-injection-inversion-rejection%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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/01/dependency-injection-inversion-rejection/"></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/01/dependency-injection-inversion-rejection/"  data-text="Dependency Injection Inversion Rejection" data-count="horizontal" data-via="davybrion">Tweet</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/01/dependency-injection-inversion-rejection/" 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/01/dependency-injection-inversion-rejection/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2010/01/dependency-injection-inversion-rejection/feed/</wfw:commentRss> <slash:comments>17</slash:comments> </item> <item><title>Real World Benefits From Loose Coupling, Inversion Of Control And Dependency Injection</title><link>http://davybrion.com/blog/2009/12/real-world-benefits-from-loose-coupling-inversion-of-control-and-dependency-injection/</link> <comments>http://davybrion.com/blog/2009/12/real-world-benefits-from-loose-coupling-inversion-of-control-and-dependency-injection/#comments</comments> <pubDate>Thu, 10 Dec 2009 06:00:16 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Code Quality]]></category> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Inversion Of Control]]></category> <category><![CDATA[Patterns]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=2000</guid> <description><![CDATA[Concepts like Dependency Injection and using an Inversion Of Control container have gradually gotten more popular and accepted in the .NET world in the last 2 years or so.&#160; There are however still quite a few people who doubt the validity of these concepts.&#160; Quite a few of these people seem to think that Dependency [...]]]></description> <content:encoded><![CDATA[<p>Concepts like Dependency Injection and using an Inversion Of Control container have gradually gotten more popular and accepted in the .NET world in the last 2 years or so.&#160; There are however still quite a few people who doubt the validity of these concepts.&#160; Quite a few of these people seem to think that Dependency Injection for instance is only useful to increase the testability of your code. I wanted to go over a real world example which shows a (IMO) huge benefit which can be solely attributed to thinking about loose coupling, using Dependency Injection and using an Inversion Of Control container.</p><p>I recently wrote a post about how you can use an <a
href="http://davybrion.com/blog/2009/12/running-an-agatha-service-layer-in-process-without-wcf/" target="_blank">Agatha service layer fully in-process instead of having to host it in a different service through WCF</a>.&#160; The only reason why it’s so easy to do that, is because Agatha’s design makes heavy use of loose coupling and dependency injection.&#160; And obviously, it makes use of an Inversion Of Control container to manage the dependencies and to wire everything together.</p><p>There are basically 3 very important parts to Agatha.&#160; The first is the Request Processor.&#160; This class basically delegates the handling of each incoming request to its corresponding request handler.&#160; The other important parts are the Request Dispatcher (for synchronous client-side usage) and the Asynchronous Request Dispatcher (for asynchronous client-side usage).&#160; I’ll just refer to these two classes as the request dispatchers for the rest of this post.&#160; When the service layer is hosted through a WCF service, the request dispatchers need to communicate with the Request Processor through a proxy (either a synchronous one, or an asynchronous one).&#160; It would’ve been very easy to tie the implementations of the request dispatchers directly to the implementation of the WCF proxies.&#160; If i had gone that way, i wouldn’t have been able to offer the ability to run the service layer in process though, since the request dispatchers would require the WCF proxies to be used.&#160; I could’ve hosted the WCF service in process, but that would really be overkill if you don’t really want to use WCF.</p><p>As easy as it would’ve been to tie the request dispatchers directly to the proxies, it was just as easy to make them depend on a slightly more abstract component.&#160; There are two interfaces to communicate with the Request Processor:</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">IRequestProcessor</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: #2b91af">Response</span>[] Process(<span
style="color: blue">params</span> <span
style="color: #2b91af">Request</span>[] requests);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">void</span> ProcessOneWayRequests(<span
style="color: blue">params</span> <span
style="color: #2b91af">OneWayRequest</span>[] requests);</p><p
style="margin: 0px">&#160;&#160;&#160; }</p><p
style="margin: 0px">&#160;</p></div><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">IAsyncRequestProcessor</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: #2b91af">IAsyncResult</span> BeginProcessRequests(<span
style="color: #2b91af">Request</span>[] requests, <span
style="color: #2b91af">AsyncCallback</span> callback, <span
style="color: blue">object</span> asyncState);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">Response</span>[] EndProcessRequests(<span
style="color: #2b91af">IAsyncResult</span> result);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">void</span> ProcessRequestsAsync(<span
style="color: #2b91af">Request</span>[] requests, <span
style="color: #2b91af">Action</span>&lt;<span
style="color: #2b91af">ProcessRequestsAsyncCompletedArgs</span>&gt; processCompleted);</p><p
style="margin: 0px">&#160;</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: #2b91af">IAsyncResult</span> BeginProcessOneWayRequests(<span
style="color: #2b91af">OneWayRequest</span>[] requests, <span
style="color: #2b91af">AsyncCallback</span> callback, <span
style="color: blue">object</span> asyncState);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">void</span> EndProcessOneWayRequests(<span
style="color: #2b91af">IAsyncResult</span> result);</p><p
style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span
style="color: blue">void</span> ProcessOneWayRequestsAsync(<span
style="color: #2b91af">OneWayRequest</span>[] requests, <span
style="color: #2b91af">Action</span>&lt;<span
style="color: #2b91af">AsyncCompletedEventArgs</span>&gt; processCompleted);</p><p
style="margin: 0px">&#160;&#160;&#160; }</p></div><p>&#160;</p><p>Notice that there are no WCF attributes on these interfaces.&#160; I have two more WCF-enabled interfaces, namely the IWcfRequestProcessor and the IAsyncWcfRequestProcessor.&#160; They define the same methods as their non-WCF counterparts, but have all of the required WCF attributes placed on top of those methods.</p><p>Typically when creating (or generating) a WCF proxy, the proxy will only implement the interface of the service contract (in this case, that would be the IWcfRequestProcessor or the IAsyncWcfRequestProcessor interface).&#160; Any class that would want to use these proxies would then need an instance of that proxy to be able to communicate with the WCF service.&#160; In Agatha’s proxies, i chose a slightly different approach.&#160; They implement both the WCF interface as well as the none-WCF interface.&#160; Since the method definitions are identical, this doesn’t require any more work.&#160; Take a look at the class definitions of those proxies:</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">RequestProcessorProxy</span> : <span
style="color: #2b91af">ClientBase</span>&lt;<span
style="color: #2b91af">IWcfRequestProcessor</span>&gt;, <span
style="color: #2b91af">IRequestProcessor</span></p></div><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">class</span> <span
style="color: #2b91af">AsyncRequestProcessorProxy</span> : <span
style="color: #2b91af">ClientBase</span>&lt;<span
style="color: #2b91af">IAsyncWcfRequestProcessor</span>&gt;, <span
style="color: #2b91af">IAsyncRequestProcessor</span></p></div><p>&#160;</p><p>As you can see, both proxy classes inherit from WCF’s ClientBase class and pass the WCF-specific interface as the generic type parameter to ClientBase.&#160; That means that these proxies can execute the WCF operations defined in the WCF-specific interface.&#160;&#160; These proxy classes also implement the original interfaces, which means that these proxies can be used by any class which requires an instance of IRequestProcessor and IAsyncRequestProcessor.</p><p>In Agatha, there is no class that directly uses either the RequestProcessorProxy or the AsyncRequestProcessorProxy class.&#160; Instead, the request dispatchers depend solely on IRequestProcessor or IAsyncRequestProcessor:</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> RequestDispatcher(<span
style="color: #2b91af">IRequestProcessor</span> requestProcessor)</p></div><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">public</span> AsyncRequestDispatcher(<span
style="color: #2b91af">IAsyncRequestProcessor</span> requestProcessor)</p></div><p>&#160;</p><p>The dispatchers never know exactly who they’re talking to.&#160; This means that they can communicate either through a WCF proxy, or the real Request Processor, depending on how your Inversion Of Control container is configured.</p><p>That is a huge benefit because it gives you a tremendous amount of flexibility when it comes to how you want to use your service layer (in process, in another service, on another machine, whatever) and it really didn’t take any extra effort with regards to development time to achieve that flexibility.&#160; If i want to use Agatha with a different communication technology, then i could do so by simply creating implementations of the IRequestProcessor and IAsyncRequestProcessor interfaces which deal with the specifics of whatever that different communication technology might be.&#160; I would also have to change the way the implementations are registered with the Inversion Of Control container to make sure that the new implementations are used.&#160; But i wouldn’t have to change anything else.</p><p>In this case, dependency injection and loose coupling was not used to increase testability.&#160; The increased testability that comes from using this approach is <em>an added bonus</em>.</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%2F12%2Freal-world-benefits-from-loose-coupling-inversion-of-control-and-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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/12/real-world-benefits-from-loose-coupling-inversion-of-control-and-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/2009/12/real-world-benefits-from-loose-coupling-inversion-of-control-and-dependency-injection/"  data-text="Real World Benefits From Loose Coupling, Inversion Of Control And Dependency Injection" data-count="horizontal" data-via="davybrion">Tweet</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/12/real-world-benefits-from-loose-coupling-inversion-of-control-and-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/2009/12/real-world-benefits-from-loose-coupling-inversion-of-control-and-dependency-injection/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2009/12/real-world-benefits-from-loose-coupling-inversion-of-control-and-dependency-injection/feed/</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>Constructor Injection vs Setter Injection</title><link>http://davybrion.com/blog/2009/11/constructor-injection-vs-sette-injection/</link> <comments>http://davybrion.com/blog/2009/11/constructor-injection-vs-sette-injection/#comments</comments> <pubDate>Mon, 02 Nov 2009 05:00:31 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Dependency Injection]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=1715</guid> <description><![CDATA[For those of you who've used Dependency Injection, you know that the two most common ways of injecting a dependency into a class are constructor injection and setter injection. For those of you who haven't used Dependency Injection yet, here's a simple example which shows both techniques: This example is very abstract, but it should [...]]]></description> <content:encoded><![CDATA[<p>For those of you who've used Dependency Injection, you know that the two most common ways of injecting a dependency into a class are constructor injection and setter injection.  For those of you who haven't used Dependency Injection yet, here's a simple example which shows both techniques:</p><div><pre class="brush: csharp; title: ; notranslate">
    public class MyService : IMyService
    {
        private IRequiredDependency requiredDependency;
 
        public IOptionalDependency OptionalDependency { get; set; }
 
        public MyService(IRequiredDependency requiredDependency)
        {
            this.requiredDependency = requiredDependency;
        }
 
        public void DoSomething()
        {
            // do something cool and/or important
            // ...
        }
    }
</pre></div><p>This example is very abstract, but it should be pretty clear.  Constructor injection is used to inject the required dependency whenever an instance of MyService is created, whereas setter injection is used to inject the optional dependency <strong>after</strong> the instance is created.  I obviously can't speak for everyone who uses Dependency Injection, but generally speaking most people use constructor injection for required dependencies and setter injection for optional dependencies.</p><p>There is however one situation in which i prefer setter injection for required dependencies over constructor injection: dependencies of abstract classes or base classes.  For instance, in our service layer each incoming request is handled by a specific RequestHandler.  Most of our RequestHandlers need our NHibernate infrastructure to be set up, which is automatically taken care of by our UnitOfWork implementation.  So we have the following NhRequestHandler class (simplified for the purpose of this blog post):</p><div><pre class="brush: csharp; title: ; notranslate">
    public abstract class NhRequestHandler&lt;TRequest, TResponse&gt; : RequestHandler&lt;TRequest, TResponse&gt;
        where TRequest : Request
        where TResponse : Response
    {
        public IUnitOfWork UnitOfWork { get; set; }
 
        public override Response Handle(Request request)
        {
            using (ITransaction transaction = UnitOfWork.CreateTransaction())
            {
                Response response;
 
                try
                {
                    response = base.Handle(request); // calls the specific Handle(TRequest) method of the derived handler
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    throw;
                }
 
                return response;
            }
        }
    }
</pre></div><p>As you can see, the IUnitOfWork dependency is a required dependency because you would get a NullReferenceException when trying to handle a request without having a IUnitOfWork instance present.  Yet, i really don't want to put it in the constructor because then each and every RequestHandler that derives from this will also have to put it in the constructor, even though most of them won't access the IUnitOfWork directly.</p><p>Actually, most of our applications inherit from the NhRequestHandler and then add some more dependencies that some kind of base BusinessRequestHandler will need.  These are dependencies to deal with authentication, authorization, user context, application context, etc... Some of these dependencies will be used by the derived RequestHandlers, some won't.  All of them however will indeed be used by the BusinessRequestHandler so they are definitely required dependencies.  Using constructor injection for these dependencies would lead to 'noise' in every derived RequestHandler's constructor.</p><p>Instead, we use setter injection for all of a base-type's dependencies, and use constructor injection only for the dependencies of the derived types.  It keeps the constructors as clean as they can be and avoids unnecessary noise.  We know that our IOC container will fulfill all the constructor dependencies as well as each property dependency in the inheritance hierarchy so there's no chance of anything going wrong there.  Unless of course somebody seriously breaks the IOC configuration but in that case, our applications won't even make it through the simplest of requests so that's not something that will ever happen unnoticed.</p><p>And for our tests, we always inherit our fixtures from things like HandlerTest or ControllerTest or whatever where all of those property dependencies are automatically set up with mocks or stubs, so it doesn't really cause problems there either.</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%2F11%2Fconstructor-injection-vs-sette-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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/11/constructor-injection-vs-sette-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/2009/11/constructor-injection-vs-sette-injection/"  data-text="Constructor Injection vs Setter Injection" data-count="horizontal" data-via="davybrion">Tweet</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/11/constructor-injection-vs-sette-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/2009/11/constructor-injection-vs-sette-injection/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2009/11/constructor-injection-vs-sette-injection/feed/</wfw:commentRss> <slash:comments>13</slash:comments> </item> <item><title>Managing your NHibernate Sessions</title><link>http://davybrion.com/blog/2008/06/managing-your-nhibernate-sessions/</link> <comments>http://davybrion.com/blog/2008/06/managing-your-nhibernate-sessions/#comments</comments> <pubDate>Sun, 22 Jun 2008 18:22:42 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Inversion Of Control]]></category> <category><![CDATA[NHibernate]]></category> <category><![CDATA[Patterns]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=149</guid> <description><![CDATA[Note: you can find a more recent post on this concept here. I was working on my northwind sample application (which i'll post about as soon as i get something that's worth showing) and i was struggling to find a clean way to manage my NHibernate sessions. I wanted a way to create a session [...]]]></description> <content:encoded><![CDATA[<p>Note: you can find a more recent post on this concept <a
href="http://davybrion.com/blog/2009/12/using-nhibernate-in-your-service-layer/">here</a>.</p><p>I was working on my northwind sample application (which i'll post about as soon as i get something that's worth showing) and i was struggling to find a clean way to manage my NHibernate sessions. I wanted a way to create a session once you enter the service layer, and that session should be available transparently to <a
href="http://martinfowler.com/eaaCatalog/repository.html">the repository</a> implementations without actually having to constantly pass it around. But i didn't just want to store it somewhere and have all the classes that needed the current session get it directly from that place. Also, i didn't want the current session to be available to everyone. Another important requirement was to have maximum flexibility for writing tests.  I could just use Rhino-Commons' implementations of the UnitOfWork and Repository patterns and be done with it, but where's the fun in that? And since this application is mostly a learning experience i figured i should try to write this myself.  After a bit of searching and experimenting, i finally came up with a way that i'm happy with (for now anyways).  Let's have a look.</p><p>To illustrate what i want, take a look at this made-up method in my service layer:</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: #2b91af;">ProductCategoryDTO</span>[] GetAllProductCategories()</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;">using</span> (<span
style="color: #2b91af;">ISession</span> session = GetNewSession())</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;">var</span> repository = GetProductCategoryRepository();</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">var</span> categories = repository.GetAllProductCategories();</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">return</span> categories.ToDTOs();</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>This is just some example code, it doesn't even work.  But it's kinda what i want... The thing is, i don't want to deal directly with the ISession type in the service layer, but i do want the ProductCategoryRepository to use the ISession that is created within the context of this method call.</p><p>NHibernate's ISession type is an implementation of the <a
href="http://www.martinfowler.com/eaaCatalog/unitOfWork.html">Unit Of Work pattern</a>. I don't want to use the ISession directly in my service layer because i want something that is a bit more high-level. Basically just something that would allow me to work within an NHibernate session, and provide me with the ability to flush changes to the database whenever i want to. And obviously, i want it to allow me to create a transaction as well.  So i came up with the following unit of work interface:</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;">interface</span> <span
style="color: #2b91af;">IUnitOfWork</span> : <span
style="color: #2b91af;">IDisposable</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> Flushes any changes that haven't been executed yet</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;/summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">void</span> Flush();</p><p
style="margin: 0px;">&nbsp;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> Creates an ITransaction instance with the ReadCommitted isolation level</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;/summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;returns&gt;&lt;/returns&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: #2b91af;">ITransaction</span> CreateTransaction();</p><p
style="margin: 0px;">&nbsp;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> Creates an ITransaction instance with the given isolation level</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;/summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;param name="isolationLevel"&gt;&lt;/param&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;returns&gt;&lt;/returns&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: #2b91af;">ITransaction</span> CreateTransaction(<span
style="color: #2b91af;">IsolationLevel</span> isolationLevel);</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>This interface pretty much offers me anything i'm concerned with in my service layer. The real implementation would do a bit more though... It has to create an NHibernate session and make it available to the repositories in a clean way.  Here's the thing though... the repositories have a completely different lifetime than the NHibernate sessions.  The NHibernate session has to be created when we enter a service method, and it has to be valid within the scope and context of the execution of that service method.  The repositories however stay alive for the lifetime of the application so they can't just hold a reference to an NHibernate session.  Every time you call a method of a repository, it has to find out which session it should use, which is the session that is being used in the context of the current service method call.  Now, we could always pass around the session but that really doesn't look good and is cumbersome.  So i basically need something that gives me access to the active nhibernate session:</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;">interface</span> <span
style="color: #2b91af;">IActiveSessionManager</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> Returns the active ISession for the current thread. Throws exception if there's</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> no active ISession instance</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;/summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;returns&gt;&lt;/returns&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: #2b91af;">ISession</span> GetActiveSession();</p><p
style="margin: 0px;">&nbsp;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> Sets the active ISession for the current thread. Throws exception if there's</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> already an active ISession instance</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;/summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;param name="session"&gt;&lt;/param&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">void</span> SetActiveSession(<span
style="color: #2b91af;">ISession</span> session);</p><p
style="margin: 0px;">&nbsp;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> Clears the active ISession for the current thread.</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;/summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">void</span> ClearActiveSession();</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>That gives me the ability to retrieve and set the active session on a per-thread basis. After all, a service method call will be handled by one thread, so setting the active session for that current thread is a convenient way to store the session.</p><p>Now i still need something that takes care of creating the NHibernate sessions:</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;">interface</span> <span
style="color: #2b91af;">ISessionFactory</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> Creates a new ISession instance</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;/summary&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: gray;">///</span><span
style="color: green;"> </span><span
style="color: gray;">&lt;returns&gt;&lt;/returns&gt;</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: #2b91af;">ISession</span> Create();</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>Ok, so what do we have so far? An interface to define the functionality that a UnitOfWork should offer at the service level.  An interface to store/retrieve the active session on the current thread, and finally, an interface to actually create the NHibernate session.  Let's start looking at the real implementations.  Here's the code to the SessionFactory class:</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;">SessionFactory</span> : <span
style="color: #2b91af;">ISessionFactory</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">private</span> <span
style="color: blue;">readonly</span> NHibernate.<span
style="color: #2b91af;">ISessionFactory</span> sessionFactory;</p><p
style="margin: 0px;">&nbsp;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">public</span> SessionFactory()</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;">Configuration</span> configuration = <span
style="color: blue;">new</span> <span
style="color: #2b91af;">Configuration</span>()</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .Configure()</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .AddAssembly(<span
style="color: #a31515;">"Northwind"</span>);</p><p
style="margin: 0px;">&nbsp;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; sessionFactory = configuration.BuildSessionFactory();</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: #2b91af;">ISession</span> Create()</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> sessionFactory.OpenSession();</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>Pretty straightforward... it initializes NHibernate and gives us the ability to ask for new sessions.  So how are we going to make these sessions available to our repositories? Through the ActiveSessionManager class of course:</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;">ActiveSessionManager</span> : <span
style="color: #2b91af;">IActiveSessionManager</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; [<span
style="color: #2b91af;">ThreadStatic</span>]</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: #2b91af;">ISession</span> current;</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: #2b91af;">ISession</span> GetActiveSession()</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> (current == <span
style="color: blue;">null</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;">InvalidOperationException</span>(<span
style="color: #a31515;">"There is no active ISession instance for this thread"</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; <span
style="color: blue;">return</span> current;</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;">void</span> SetActiveSession(<span
style="color: #2b91af;">ISession</span> session)</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> (current != <span
style="color: blue;">null</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;">InvalidOperationException</span>(<span
style="color: #a31515;">"There is already an active ISession instance for this thread"</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; current = session;</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;">void</span> ClearActiveSession()</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; current = <span
style="color: blue;">null</span>;</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>It basically just stores the session in a ThreadStatic field, which means that each thread will have a different static reference for this field. So if we set the active session through the SetActiveSession method in thread X, and thread Y also sets an active session, the GetActiveSession method will return the correct session instances for each thread.</p><p>So now we have everything we need to create our UnitOfWork class:</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;">UnitOfWork</span> : <span
style="color: #2b91af;">Disposable</span>, <span
style="color: #2b91af;">IUnitOfWork</span></p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">private</span> <span
style="color: blue;">readonly</span> <span
style="color: #2b91af;">IActiveSessionManager</span> activeSessionManager;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">private</span> <span
style="color: blue;">readonly</span> <span
style="color: #2b91af;">ISession</span> session;</p><p
style="margin: 0px;">&nbsp;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">public</span> UnitOfWork(<span
style="color: #2b91af;">ISessionFactory</span> sessionFactory, <span
style="color: #2b91af;">IActiveSessionManager</span> activeSessionManager)</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>.activeSessionManager = activeSessionManager;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; session = sessionFactory.Create();</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; activeSessionManager.SetActiveSession(session);</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;">protected</span> <span
style="color: blue;">override</span> <span
style="color: blue;">void</span> DisposeObjects()</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> (session != <span
style="color: blue;">null</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; session.Close();</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; session.Dispose();</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;">protected</span> <span
style="color: blue;">override</span> <span
style="color: blue;">void</span> ClearReferences()</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; activeSessionManager.ClearActiveSession();</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;">void</span> Flush()</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; session.Flush();</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: #2b91af;">ITransaction</span> CreateTransaction()</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> CreateTransaction(<span
style="color: #2b91af;">IsolationLevel</span>.ReadCommitted);</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: #2b91af;">ITransaction</span> CreateTransaction(<span
style="color: #2b91af;">IsolationLevel</span> isolationLevel)</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> session.BeginTransaction(isolationLevel);</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>When the UnitOfWork is created, it receives an ISessionFactory instance, and an IActiveSessionManager instance. It then creates a new session through the ISessionFactory and uses the IActiveSessionManager to make sure that session is the active session for the current thread.  When the UnitOfWork is disposed, it closes and cleans up the session and it also uses the IActiveSessionManager to clear the active session for the current thread.  Oh and it obviously also provides implementations for what it is we actually need in our service layer: flushing the changes whenever we want and creating transactions.</p><p>The ISessionFactory and IActiveSessionManager instances should stay alive as long as the application is alive.  But as you could see in the implementations of those types, we didn't write any code to deal with their lifetimes.  I'm actually relying on my IoC container for that. In the class where my container is set up, you'll find the following code:</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;">private</span> <span
style="color: blue;">static</span> <span
style="color: blue;">void</span> RegisterUnitOfWorkComponents()</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; Register(<span
style="color: #2b91af;">Component</span>.For&lt;<span
style="color: #2b91af;">ISessionFactory</span>&gt;()</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .ImplementedBy&lt;<span
style="color: #2b91af;">SessionFactory</span>&gt;().LifeStyle.Singleton);</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Register(<span
style="color: #2b91af;">Component</span>.For&lt;<span
style="color: #2b91af;">IActiveSessionManager</span>&gt;()</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .ImplementedBy&lt;<span
style="color: #2b91af;">ActiveSessionManager</span>&gt;().LifeStyle.Singleton);</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Register(<span
style="color: #2b91af;">Component</span>.For&lt;<span
style="color: #2b91af;">IUnitOfWork</span>&gt;()</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .ImplementedBy&lt;<span
style="color: #2b91af;">UnitOfWork</span>&gt;().LifeStyle.Transient);</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>ISessionFactory and IActiveSessionManager are registered as singleton instances, so whenever these types are requested, the same instances will be returned.  The IUnitOfWork type is registered with a transient lifetime, so whenever it is requested, the container will create a new UnitOfWork class and pass the ISessionFactory and IActiveSessionManager instances to the constructor.</p><p>Right, we've taken care of creating the session, associating it with the current thread and making it available in a nice and clean way.  Now we actually have to make sure our repositories can use it.  In the base repository implementation, you can find the following code:</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;">private</span> <span
style="color: blue;">readonly</span> <span
style="color: #2b91af;">IActiveSessionManager</span> activeSessionManager;</p><p
style="margin: 0px;">&nbsp;</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">public</span> Repository(<span
style="color: #2b91af;">IActiveSessionManager</span> activeSessionManager)</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>.activeSessionManager = activeSessionManager;</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;">protected</span> <span
style="color: #2b91af;">ISession</span> Session</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;">get</span> { <span
style="color: blue;">return</span> activeSessionManager.GetActiveSession(); }</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p></div><p></code></p><p>Whenever a repository needs a session, it just needs to use the protected Session property and it will get the session that is associated with the current thread.</p><p>So now we can rewrite our made-up service method from earlier to the following:</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: #2b91af;">ProductCategoryDTO</span>[] GetAllProductCategories()</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;">using</span> (<span
style="color: #2b91af;">Container</span>.Resolve&lt;<span
style="color: #2b91af;">IUnitOfWork</span>&gt;())</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;">var</span> repository = <span
style="color: #2b91af;">Container</span>.Resolve&lt;<span
style="color: #2b91af;">ProductCategoryRepository</span>&gt;();</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">var</span> categories = repository.GetAllProductCategories();</p><p
style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span
style="color: blue;">return</span> categories.ToDTOs();</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>We know that the NHibernate session will be created, and more importantly, that it is not just globally accessible to everyone.  It can only be accessed when you have a reference to an IActiveSessionManager instance.  We also don't need to pass around the session all the time so our code is a bit more concise, showing only the intent of what we're trying to do without distracting us with details that are not relevant to that intent.  We also have a lot of flexibility to write tests... i can write tests for my repositories without having to create a UnitOfWork... i can simply pass a fake IActiveSessionManager to my repositories when i'm testing them and have it return the session that i'm using for my test.  All in all, this approach offers me with a lot of advantages, without ugly disadvantages.  Well, at this moment i don't really see any disadvantages so if you do see some, please let me know <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%2F06%2Fmanaging-your-nhibernate-sessions%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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/managing-your-nhibernate-sessions/"></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/managing-your-nhibernate-sessions/"  data-text="Managing your NHibernate Sessions" data-count="horizontal" data-via="davybrion">Tweet</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/managing-your-nhibernate-sessions/" 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/managing-your-nhibernate-sessions/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/06/managing-your-nhibernate-sessions/feed/</wfw:commentRss> <slash:comments>39</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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>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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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">Tweet</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> <item><title>The DI discussion continues&#8230;</title><link>http://davybrion.com/blog/2007/08/the-di-discussion-continues/</link> <comments>http://davybrion.com/blog/2007/08/the-di-discussion-continues/#comments</comments> <pubDate>Wed, 22 Aug 2007 06:52:23 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[testing]]></category><guid
isPermaLink="false">http://ralinx.wordpress.com/2007/08/22/the-di-discussion-continues/</guid> <description><![CDATA[Round 3: Jacob and Ayende continue to discuss DI on their blogs. It seems that Jacob thinks that DI brings a lot of development overhead with it, which i couldn't disagree with more. That is, if you don't go overboard with the DI usage. I use DI where it makes sense to me, not because [...]]]></description> <content:encoded><![CDATA[<p>Round 3:</p><p><a
href="http://scruffylookingcatherder.com/archive/2007/08/20/poking-bears.aspx">Jacob</a> and <a
href="http://ayende.com/Blog/archive/2007/08/21/Dependency-Injection-Applicability-Benefits-and-Mocking.aspx">Ayende</a> continue to discuss DI on their blogs.</p><p>It seems that Jacob thinks that DI brings a lot of development overhead with it, which i couldn't disagree with more. That is, if you don't go overboard with the DI usage. I use DI where it makes sense to me, not because it's fashionable or because it's what the cool developers tell me to use. I mostly use it in places where it takes away from the development overhead, in the form of easy testability and perhaps even more important: fast tests. Nobody likes to run slow tests so getting them as fast as you can, while still correctly covering the functionality that you want to test should be one of your goals if you're doing TDD.</p><p>So where does that leave DI? Well, i mostly use it when i want to test code that is dependent on components that can either be slow, or have erratic/unpredictable behaviour. And sometimes i'll use it just because it makes something a lot easier to test. I certainly don't use DI for each and every dependency in my code. This approach certainly doesn't bring a lot of development overhead with it since it's rather easy to do. Initially while coding, it might cost you a few more minutes. But that's really not a lot is it? The time i save while being able to run my entire test suite in a matter of seconds whenever i make a change or add a new feature more than makes up for those few minutes i lost initially.</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%2F2007%2F08%2Fthe-di-discussion-continues%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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/2007/08/the-di-discussion-continues/"></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/2007/08/the-di-discussion-continues/"  data-text="The DI discussion continues&#8230;" data-count="horizontal" data-via="davybrion">Tweet</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/2007/08/the-di-discussion-continues/" 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/2007/08/the-di-discussion-continues/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2007/08/the-di-discussion-continues/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Dependency Injection discussion</title><link>http://davybrion.com/blog/2007/08/dependency-injection-discussion/</link> <comments>http://davybrion.com/blog/2007/08/dependency-injection-discussion/#comments</comments> <pubDate>Sun, 19 Aug 2007 11:39:43 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[testing]]></category><guid
isPermaLink="false">http://ralinx.wordpress.com/2007/08/19/dependency-injection-discussion/</guid> <description><![CDATA[This post shamelessly links to a few other posts, but this is a pretty good discussion about the benefits of dependency injection (DI) and definitely a good read. Round 1: It starts off with Jacob Proffitt's post where he challenges the benefits of DI beyond those of testability. Ayende then posted a good reply to [...]]]></description> <content:encoded><![CDATA[<p>This post shamelessly links to a few other posts, but this is a pretty good discussion about the benefits of dependency injection (DI) and definitely a good read.</p><p>Round 1:</p><p>It starts off with Jacob Proffitt's <a
href="http://scruffylookingcatherder.com/archive/2007/08/07/dependency-injection.aspx">post</a> where he challenges the benefits of DI beyond those of testability.  Ayende then posted <a
href="http://ayende.com/Blog/archive/2007/08/18/Dependency-Injection-More-than-a-testing-seam.aspx">a good reply</a> to it.  Nate Kohari also has an excellent <a
href="http://kohari.org/2007/08/15/defending-dependency-injection/">post</a> defending DI.</p><p>Round 2:</p><p>Jacob <a
href="http://scruffylookingcatherder.com/archive/2007/08/16/tilting-at-windmills.aspx">replies</a>, followed again by another Ayende <a
href="http://ayende.com/Blog/archive/2007/08/18/Dependency-Injection-IAmDonQuixote.aspx">reply</a>.  Aaron from Eleutian then chips in with another <a
href="http://blog.eleutian.com/2007/08/18/DependencyInjectionTypeMockWindmillsAndOtherStuff.aspx">thoughtful post</a>.</p><p>You're probably wondering: "why the hell is he just linking to these posts?".  Well, i just like DI and wish more developers knew about it.  For those who don't know too much about DI, read my <a
href="http://davybrion.com/blog/2007/07/introduction-to-dependency-injection/">intro to DI</a> and then read all of the posts i linked to above.  You should have a pretty good understanding of DI and its benefits then.</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%2F2007%2F08%2Fdependency-injection-discussion%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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/2007/08/dependency-injection-discussion/"></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/2007/08/dependency-injection-discussion/"  data-text="Dependency Injection discussion" data-count="horizontal" data-via="davybrion">Tweet</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/2007/08/dependency-injection-discussion/" 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/2007/08/dependency-injection-discussion/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2007/08/dependency-injection-discussion/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Introduction to Dependency Injection</title><link>http://davybrion.com/blog/2007/07/introduction-to-dependency-injection/</link> <comments>http://davybrion.com/blog/2007/07/introduction-to-dependency-injection/#comments</comments> <pubDate>Tue, 31 Jul 2007 21:08:36 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Dependency Injection]]></category> <category><![CDATA[Software Development]]></category> <category><![CDATA[testing]]></category><guid
isPermaLink="false">http://ralinx.wordpress.com/2007/07/31/introduction-to-dependency-injection/</guid> <description><![CDATA[Dependency Injection (DI) is an incredibly useful and easy technique which makes your code a lot easier to test (that's not the only benefit though). But i've noticed that there are still plenty of developers who don't know what it is, or have heard of it but don't know how to use it, etc... Hopefully, [...]]]></description> <content:encoded><![CDATA[<p>Dependency Injection (DI) is an incredibly useful and easy technique which makes your code a lot easier to test (that's not the only benefit though).  But i've noticed that there are still plenty of developers who don't know what it is, or have heard of it but don't know how to use it, etc... Hopefully, it'll be somewhat clear after reading this <img
src='http://d18sni7re4ly7f.cloudfront.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><p>I like to use 'real' examples so i'll try to explain DI based on some code i wrote for Noma yesterday. I have a SqlMetaDataProvider class which needs to provide me with meta data coming from a SQL Server database.  It retrieves the meta data from the database in a relational structure (a DataSet) and then converts it to an easy to use object model.  Obviously, i want to be able to test this class without actually going to the database because that would make my tests slow.  So how can we test if the relational data is being converted to the object model without going to the database?</p><p>Well, let's look at what the class does. First of all, it retrieves sql server meta data. Then it converts it to an object model.  But retrieving the meta data doesn't really belong here... it should be functionality that's offered by another class.  So we create a SqlDataRetriever class.  All it will do is return meta data in the relational structure. Nothing more. So now, our SqlMetaDataProvider class can simply use the SqlDataRetriever class to retrieve the meta data.  So basically, SqlDataRetriever is now a dependency of the SqlMetaDataProvider class because SqlMetaDataProvider is depending on SqlDataRetriever to return the relational meta data.</p><p>At this point, our class could look like this:</p><div><pre class="brush: csharp; title: ; notranslate">
public class SqlMetaDataProvider : IMetaDataProvider
{
    private readonly string _connectionString;
    private readonly SqlDataRetriever _sqlDataRetriever;
 
    public SqlMetaDataProvider(string connectionString)
    {
        _connectionString = connectionString;
        _sqlDataRetriever = new SqlDataRetriever();
    }
 
    public MetaDataStore GetMetaDataStore()
    {
        SqlMetaData sqlMetaData = _sqlDataRetriever.GetMetaData(_connectionString);

        return ConvertToMetaDataStore(sqlMetaData);
    }

    private MetaDataStore ConvertToMetaDataStore(SqlMetaData sqlMetaData)
    {
        MetaDataStore store = new MetaDataStore();

        AddTablesToStore(sqlMetaData.TableInfo, store);
        AddColumnsToTablesInStore(sqlMetaData.ColumnInfo, store);
        CreateRelationshipsBetweenTables(sqlMetaData.RelationshipInfo, store);

        return store;
    }
}
</pre></div><p>Note: I left out the code for the AddTablesToStore, AddColumnsToTablesInStore and CreateRelationshipsBetweenTables methods because they aren't relevant to this specific topic.</p><p>Now we need to make sure we can replace the instance of SqlDataRetriever during testing with one we can supply ourselves. That test instance could then simply return a DataSet that was created in-memory, thus keeping our tests running fast. Notice how SqlMetaDataProvider has a reference of the type SqlDataRetriever. The type is essentially fixed, which creates a strong dependency on the SqlDataRetriever class.  If we were to replace the type of the reference with an interface, it would at least make it easier to use another type for our required dependency, one that simply implements the interface.</p><p>So we create the ISqlDataRetriever interface:</p><div><pre class="brush: csharp; title: ; notranslate">
public interface ISqlDataRetriever
{
    SqlMetaData GetMetaData(string connectionString);
}
</pre></div><p>And then we modify the definition of SqlDataRetriever to implement the interface:</p><div><pre class="brush: csharp; title: ; notranslate">
public class SqlDataRetriever : ISqlDataRetriever
</pre></div><p>Now we need to modify our SqlMetaDataProvider class so it holds a reference to the interface type, instead of the class type:</p><div><pre class="brush: csharp; title: ; notranslate">
    private readonly ISqlDataRetriever _sqlDataRetriever;
</pre></div><p>We still need to find a way to inject our dependency into our SqlMetaDataProvider so we'll modify the constructor:</p><div><pre class="brush: csharp; title: ; notranslate">
public SqlMetaDataProvider(string connectionString, ISqlDataRetriever sqlDataRetriever)
{
    _connectionString = connectionString;
    _sqlDataRetriever = sqlDataRetriever;
}
</pre></div><p>The only downside to this is that it now takes more work to create an instance of SqlMetaDataProvider... work that clients shouldn't need to do if they just want to use the default ISqlDataRetriever implementation.  If you're using an Inversion Of Control (IoC) container, you can simply request an instance of SqlMetaDataProvider and the IoC container would also create the necessary dependency for you.  Using an IoC container however is outside of the scope for this post, so we won't do that. In fact, if you know that your production code will always use the SqlDataRetriever implementation, you could also provide a simpler  constructor which takes care of that for you:</p><div><pre class="brush: csharp; title: ; notranslate">
public SqlMetaDataProvider(string connectionString)
        : this(connectionString, new SqlDataRetriever()) {}
</pre></div><p>So you could use the simpler constructor in your production code, and the other one in your test code.  Speaking of test code, we still need to write that test which tests the conversion without hitting the database.  First, we need to create an implementation of ISqlDataRetriever which allows us to pass a DataSet to it which the ISqlDataRetriever instance should return to its consumer (our SqlMetaDataProvider):</p><div><pre class="brush: csharp; title: ; notranslate">
    public class SqlDataProviderStub : ISqlDataRetriever
    {
        private SqlMetaData _sqlMetaData;
 
        public SqlMetaData SqlMetaData
        {
            set { _sqlMetaData = value; }
        }
 
        SqlMetaData ISqlDataRetriever.GetMetaData(string connectionString)
        {
            return _sqlMetaData;
        }
    }            
</pre></div><p>And finally, the test:</p><div><pre class="brush: csharp; title: ; notranslate">
        [Test]
        public void GetMetaDataStore_ProvideDataSetWithTwoTablesAndRelationship_MetaDataStoreIsCorrect()
        {
            SqlMetaData sqlMetaData = PrepareMetaDataSetInMemoryWithTestData();
 
            SqlDataProviderStub sqlDataProvider = new SqlDataProviderStub();
            sqlDataProvider.SqlMetaData = sqlMetaData;
 
            // pass null as the connectionString, and pass our SqlDataProviderStub
            IMetaDataProvider metaDataProvider = new SqlMetaDataProvider(null, sqlDataProvider);
 
            MetaDataStore store = metaDataProvider.GetMetaDataStore();
 
            AssertStoreContainsOurTestData(store);
        }
</pre></div><p>Mission accomplished <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%2F2007%2F07%2Fintroduction-to-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" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></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/2007/07/introduction-to-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/2007/07/introduction-to-dependency-injection/"  data-text="Introduction to Dependency Injection" data-count="horizontal" data-via="davybrion">Tweet</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/2007/07/introduction-to-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/2007/07/introduction-to-dependency-injection/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2007/07/introduction-to-dependency-injection/feed/</wfw:commentRss> <slash:comments>3</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/67 queries in 0.036 seconds using disk: basic
Object Caching 1342/1479 objects using disk: basic
Content Delivery Network via Amazon Web Services: CloudFront: d18sni7re4ly7f.cloudfront.net

Served from: davybrion.com @ 2012-02-08 05:38:48 -->
