/atom.xml
XML | 3407 lines | 2953 code | 441 blank | 13 comment | 0 complexity | c1da7adda36d3fc8816553280e9e26fc MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <?xml version="1.0" encoding="utf-8"?>
- <feed xmlns="http://www.w3.org/2005/Atom">
- <title><![CDATA[Curried Functions]]></title>
- <link href="http://efvincent.github.io/atom.xml" rel="self"/>
- <link href="http://efvincent.github.io/"/>
- <updated>2014-08-18T13:03:44-04:00</updated>
- <id>http://efvincent.github.io/</id>
- <author>
- <name><![CDATA[Eric F. Vincent]]></name>
-
- </author>
- <generator uri="http://octopress.org/">Octopress</generator>
-
- <entry>
- <title type="html"><![CDATA[Debounce as a Directive]]></title>
- <link href="http://efvincent.github.io/blog/2014/08/18/debounce-as-a-directive/"/>
- <updated>2014-08-18T01:28:33-04:00</updated>
- <id>http://efvincent.github.io/blog/2014/08/18/debounce-as-a-directive</id>
- <content type="html"><![CDATA[<p>Some months ago a co-worker asked if there were a way to buffer the input on a text box
- so that the handler would not be called more than every X milliseconds. His app was doing
- the fairly typical chore of searching through a long list as the user types into a
- search box. Firing a <code>digest</code> (that’s Angular’s re-bind and re-render loop) for each
- keystroke causes a jumpy, jittery refresh storm.</p>
- <p>What he was looking for is commonly referred to as to <em>debounce</em> or <em>throttle</em> a
- function. There are many implementations around, but his question was specifically
- about debounce in the context of Angular, preferably as a directive.</p>
- <!-- more -->
- <p>I found a snippet authored by <a href="http://tommaitland.net">Tom Maitland</a> that does just
- what we need. I tweaked it slightly (also as a <a href="https://gist.github.com/efvincent/9784923">Gist</a>
- and <a href="http://jsfiddle.net/efvincent/vkphp2fa/">JSFiddle</a>):</p>
- <div><table class="CodeRay"><tr>
- <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
- <a href="#n2" name="n2">2</a>
- <a href="#n3" name="n3">3</a>
- <a href="#n4" name="n4">4</a>
- <a href="#n5" name="n5">5</a>
- <a href="#n6" name="n6">6</a>
- <a href="#n7" name="n7">7</a>
- <a href="#n8" name="n8">8</a>
- <a href="#n9" name="n9">9</a>
- <strong><a href="#n10" name="n10">10</a></strong>
- <a href="#n11" name="n11">11</a>
- <a href="#n12" name="n12">12</a>
- <a href="#n13" name="n13">13</a>
- <a href="#n14" name="n14">14</a>
- <a href="#n15" name="n15">15</a>
- <a href="#n16" name="n16">16</a>
- <a href="#n17" name="n17">17</a>
- <a href="#n18" name="n18">18</a>
- <a href="#n19" name="n19">19</a>
- <strong><a href="#n20" name="n20">20</a></strong>
- <a href="#n21" name="n21">21</a>
- <a href="#n22" name="n22">22</a>
- <a href="#n23" name="n23">23</a>
- <a href="#n24" name="n24">24</a>
- <a href="#n25" name="n25">25</a>
- <a href="#n26" name="n26">26</a>
- </pre></td>
- <td class="code"><pre><span class="comment">// Defines the module as "app", this is not best practice for module</span>
- <span class="comment">// definition or project structure, focus on the directive</span>
- angular.module(<span class="string"><span class="delimiter">'</span><span class="content">app</span><span class="delimiter">'</span></span>, []).directive(<span class="string"><span class="delimiter">'</span><span class="content">tlDebounce</span><span class="delimiter">'</span></span>, <span class="keyword">function</span>(<span class="predefined">$timeout</span>) {
- <span class="keyword">return</span> {
- <span class="key">restrict</span>: <span class="string"><span class="delimiter">'</span><span class="content">A</span><span class="delimiter">'</span></span>,
- <span class="key">require</span>: <span class="string"><span class="delimiter">'</span><span class="content">ngModel</span><span class="delimiter">'</span></span>,
- <span class="key">priority</span>: <span class="integer">99</span>,
- <span class="function">link</span>: <span class="keyword">function</span>(scope, elm, attr, ngModelCtrl) {
- <span class="keyword">if</span> (attr.type === <span class="string"><span class="delimiter">'</span><span class="content">radio</span><span class="delimiter">'</span></span> || attr.type === <span class="string"><span class="delimiter">'</span><span class="content">checkbox</span><span class="delimiter">'</span></span>) <span class="keyword">return</span>;
- elm.unbind(<span class="string"><span class="delimiter">'</span><span class="content">input</span><span class="delimiter">'</span></span>);
- <span class="keyword">var</span> debounce;
- elm.bind(<span class="string"><span class="delimiter">'</span><span class="content">input</span><span class="delimiter">'</span></span>, <span class="keyword">function</span>() {
- <span class="predefined">$timeout</span>.cancel(debounce);
- ngModelCtrl.<span class="predefined">$setViewValue</span>(elm.val());
- }, attr.tlDebounce || <span class="integer">1000</span>);
- });
- elm.bind(<span class="string"><span class="delimiter">'</span><span class="content">blur</span><span class="delimiter">'</span></span>, <span class="keyword">function</span>() {
- scope.<span class="predefined">$apply</span>(<span class="keyword">function</span>() {
- ngModelCtrl.<span class="predefined">$setViewValue</span>(elm.val());
- });
- });
- }
- }
- });
- </pre></td>
- </tr></table>
- </div>
- <h2 id="examining-the-directive">Examining the directive</h2>
- <p>The directive starts at line 3 by defining a module and calling the <code>directive</code> function
- which causes Angular to register a directive in that module. This directive is called <code>tlBounce</code>.
- To define a directive we pass a function and our function returns a directive definition object.</p>
- <h3 id="injecting-angulars-timer-service">Injecting Angular’s Timer service</h3>
- <p>The debounce directive will use a timer to assure that when attached to a text box, the underlying
- model will only be updated every X milliseconds. We’ll see the algorithm in a bit.</p>
- <p>When Angular needs an instance of our directive, it will call the function we’ve provided. Angular
- will inspect the function and detect that it has a dependency; to call the function Angular must
- provide, or <em>inject</em> something called <code>$timeout</code>, which is one of Angular’s services. Angular offers
- many <em>services</em> to you as the application developer to use in creating a directive (or factory,
- filter, controller, or the other Angular things). These services are objects or functions provided by the framework.</p>
- <p>The tip-off that <code>$timeout</code> is a service is the leading dollar sign. Angular will use its
- <a href="https://docs.angularjs.org/api/auto/service/$injector#!">Injector</a> service to find a <code>$timeout</code> and pass it
- to us. We’ll then use the <code>$timeout</code> in our <em>link function</em>.</p>
- <h3 id="the-link-function">The link function</h3>
- <p>Without getting into the guts of directive development, suffice it to say that in most
- cases when writing a directive you’ll want to focus on the <code>link</code> function. For more information
- on the link function, there’s the <a href="http://angularjs.org/">Angular Docs</a>, and another good source of information is
- <a href="http://www.angularjshub.com/examples/customdirectives/compilelinkfunctions/">AngularJS Hub</a>.</p>
- <p>The <code>link</code> function sets up each instance of the directive. You supply the function that can have
- up to four parameters. <code>link: function(scope, elm, attr, ngModelCtrl)</code>.</p>
- <h4 id="link-function-parameters">Link function parameters</h4>
- <p>The first is the directive’s local scope, which is usually used like you use scope in a controller
- to maintain and bind to the internal state of the directive. We’ll see how <code>scope</code> is used here in a second.</p>
- <p>Second is the <code>elm</code> or <em>element</em> parameter. This is the DOM element that the directive to which the
- directive is attached. For debounce, the directive is attached to an input, usually a text box. You can do the
- usual DOM-stuff to the element, attach event handlers, change content, add children, etc. AAMOF you actually
- have an Angular wrapper around the element, so you get some additional JQuery like functions on the element.</p>
- <p>Third is <code>attr</code>, the attributes. This is a map of the attributes on the element to which our directive is
- attached. In our case, we’re using the <code>attr</code> to detect if we’re attached to a radio button or check box; our
- deBounce doesn’t have a meaning for those controllers, so we bail if we see that we’re attached to one (line 9).</p>
- <p>Lastly is the <code>ngModelCtrl</code>, which is the least intuitive. This is a controller requirement of our directive,
- it says that any directive we’re attached to needs to have an <code>ngModelCtrl</code> controller. This sort of limits
- our deBouncer, but the target use case is to put this directive on a text box that’s using AngularJS’s binding.</p>
- <h3 id="debounce-algorithm">DeBounce Algorithm</h3>
- <p>The strategy is as follows:</p>
- <ol>
- <li>Detach the input handler (line 11) that usually updates the model</li>
- <li>Bind a new input handler
- <ol>
- <li>Cancel any pending debounce timer (line 15)</li>
- <li>Set up a new debounce timer
- <ol>
- <li>It should go off in the time specified by the <code>tl-debounce</code> attribute, or 1,000ms if the attribute is
- not specified (line 18).</li>
- </ol>
- </li>
- <li>When it goes off, it should tell the model controller <code>ngModelCtrl</code> to set it’s value <code>.$setViewValue(elm.val())</code></li>
- </ol>
- </li>
- <li>Bind a new blur handler, so when th user leaves the field the model is always updated.
- <ol>
- <li>Put the call to <code>$setNewValue()</code> inside a <code>scope.apply()</code> so the change causes a digest (Angular rebinds everything).</li>
- </ol>
- </li>
- </ol>
- <h3 id="the-digest">The Digest</h3>
- <p>One important point - you may be thinking that you could have used the standard JavaScript timer. Why
- use Angular’s <code>$timer</code> service? It’s because Angular needs to know when the model changes so that it
- can perform it’s two way binding / model-view synchronization. By using Angular’s timer, you can be assured
- that Angular will know when the timer goes off and will do all the right Angular binding stuff at that time.</p>
- <h3 id="but-eric-youre-wrong-and-oh-so-stupid">But Eric, you’re wrong and oh so stupid!</h3>
- <blockquote>
- <p>You <strong>could</strong> use the normal timer, because when you call <code>.$setViewValue()</code>
- you’re letting Angular know something needs to change, right? I mean, it starts in a dollar sign,
- so it’s all Angulary, right? </p>
- </blockquote>
- <p>Heh. You’d think so, but you’d be wrong. This is the kind of thing that makes you scratch your head, then waste
- fifteen minutes, then look up the docs, then unleash a stream of profanities. It happens that <code>.$setViewValue()</code> does
- <strong>not</strong> cause a digest, probably because of performance or some other really good reason. Doesn’t make it fun though, and
- it’s the kind of undiscoverable crap that qualifies as a legit complaint about AngularJS. Take your medicine.</p>
- <p>So that’s DeBounce - it actually works pretty well for things like text boxes that do searches and stuff like that.
- I use it in production, but there’s no warrentee so YMMV. Have a good one…</p>
- <p>-e</p>
- ]]></content>
- </entry>
-
- <entry>
- <title type="html"><![CDATA[GitHubify(Blog)]]></title>
- <link href="http://efvincent.github.io/blog/2014/08/15/Octopress-github-ruby-windows/"/>
- <updated>2014-08-15T12:00:11-04:00</updated>
- <id>http://efvincent.github.io/blog/2014/08/15/Octopress-github-ruby-windows</id>
- <content type="html"><![CDATA[<p>For my shiney new blog I decided to go full hipster and host on GitHub. This means that
- the entire site, source code as well as the blog website itself, can be seen at
- <a href="https://github.com/efvincent/efvincent.github.io">my blog’s repository</a>. Of course all of this will be painfully
- uncool by this time next year. But for the time being it’s fun and the tech is relevant.</p>
- <p>Dig in if you want to see the ins and outs of setting all this up on a Windows workstation,
- because Windows is so far out of fashion stuff is starting to not work on it by default. Karma.
- <!--more -->
- ## Static Site Generation
- The way GitHub hosted web sites work is that the entire web site is pure static HTML,
- JavaScript, and CSS. If you work in the industry you realize that all the web site
- frameworks (server side) like JSP, ASP.NET, Rails, PHP, etc. all <em>generate</em> pages on
- the fly as the requests come in. This requires a server be running somewhere that can
- run .NET, Java, Ruby, or whatever.</p>
- <p>A static site everything is pre-generated, so any server that can respond to requests
- by serving up a file can host a static site. But no one want’s to hand craft HTML pages
- for every blog post. So what you have is a generator; some kind of program that can take
- blog posts written in plain text and <strong>poof!</strong> Generate a static website.</p>
- <p>The basic idea is that you have a <em>source</em> directory that has your blog posts written
- in (typically) <a href="https://en.wikipedia.org/wiki/Markdown">markdown</a>, CSS, templates for HTML,
- and the Ruby / JavaScript / whatever that the generator is written in.</p>
- <p>There’s typically a command line interface; so you issue the proper command the
- generator takes your markdown and creates a complete, static web site.</p>
- <h2 id="github">GitHub</h2>
- <p>That’s where <a href="www.github.com">GitHub</a> comes in. If you don’t know what GitHub is, or
- if you’re completely lost at this point, then you probably need to hit up this
- <a href="https://www.youtube.com/watch?v=oHg5SJYRHA0">everything you need to know to become a modern developer</a>
- tutorial.</p>
- <p>Think about it for two seconds, it makes perfect sense. GitHub hosts files in a repository and is a web site.
- So if you put a static web site’s worth of files <em>in a repository</em>, and GitHub does a tiny bit of magic, it
- can serve those web pages up. And that’s all a GitHub hosted static site is. You write posts in
- markdown, you use a generator to create a static site, and you check it into GitHub.</p>
- <h2 id="octopress">OctoPress</h2>
- <p>I admittedly don’t have a ton of experience with static site generators. I played with
- a couple before committing to <a href="www.octopress.org">Octopress</a>. At first I wanted to
- use a <a href="http://nodejs.org">Node.js</a> based static site generator. I googled around a bit
- and ended up playing with <a href="https://github.com/jnordberg/wintersmith">Wintersmith</a> for
- a night. It worked, but GitHub makes it easiest to use a Ruby based generator called <a href="http://jekyllrb.com">Jekyll</a>.
- A bit more poking around and I ended up with <a href="www.octopress.org">Octopress</a>, which is
- built on top of Jekyll, offers additional features, and incredibly well written, well
- documented, and easy to use.</p>
- <p>When you go to their site you’ll get walked through the installation step by step,
- and there are some nice Ruby build tools available to get things moving, including
- configuring your new Octopress generator to work with GitHub web sites. <strong>Highly recommended</strong></p>
- <h2 id="ruby">Ruby</h2>
- <p>Ok so <a href="https://www.youtube.com/watch?v=gBkDvqIGSaE">Ruby hates Windows</a>. It might be passive,
- but the ill feelings are there. Which is fine, everyone can’t love everyone, and Microsoft
- has kinda earned it by being a dick until very recently. But whatever, I’m not with starting
- flame war. It happens that I still use Windows for all kinds of reasons, so I needed to
- get Ruby on my workstation.</p>
- <p>Actually I had installed Ruby using <a href="http://chocolatey.org/">Chocolately</a> because I
- love playing with all the languages, but to run Jekyll you’ll need the
- <a href="http://rubyinstaller.org/downloads/">Ruby Development Kit</a>. The RDK is platform
- specific, and is needed to build <em>gems</em> (Ruby packages) that are platform specific,
- which Jekyll either is or depends on indirectly (I didn’t check).</p>
- <p>There are <a href="https://github.com/oneclick/rubyinstaller/wiki/Development-Kit">very clear instructions</a>
- that you can follow for getting this set up. Once that’s done you can play along with
- the <a href="www.octopress.org">Octopress</a> setup instructions, which are great. Just follow the
- track that has you deploy to GitHub.</p>
- ]]></content>
- </entry>
-
- <entry>
- <title type="html"><![CDATA[Abandonment Issues]]></title>
- <link href="http://efvincent.github.io/blog/2014/08/15/abandonment-issues/"/>
- <updated>2014-08-15T11:52:11-04:00</updated>
- <id>http://efvincent.github.io/blog/2014/08/15/abandonment-issues</id>
- <content type="html"><![CDATA[<p>I’ve moved my blog from WordPress on my own personal site to GitHub, because … GitHub of course. <em>No One</em> is going
- to miss my other blog. It had a couple of what I thought were interesting posts on F# and dependency injection in C#. But it’s time
- for a fresh start.</p>
- <p>Expect posts on JavaScript and front end development for a little while. After a career spent designing relational
- databases for finance, insurance and other LOB domains, I’ve been working on SPA style front end enterprise applications for
- a couple of years. And it’s fun. I may actually have a couple of interesting things to say. We’ll see.</p>
- ]]></content>
- </entry>
-
- <entry>
- <title type="html"><![CDATA[DI – Constructor Injection, Bootstrapping]]></title>
- <link href="http://efvincent.github.io/blog/2011/06/24/di-bootstrap/"/>
- <updated>2011-06-24T02:07:31-04:00</updated>
- <id>http://efvincent.github.io/blog/2011/06/24/di-bootstrap</id>
- <content type="html"><![CDATA[<h2 id="constructor-injection">Constructor Injection</h2>
- <p>The idea of dependency injection is that classes are defined such that any dependencies on other classes or services, are <em>injected</em> into the class by some external mechanism, as opposed to being “newed up” directly. The most common form of DI is constructor injection, where a class defines a constructor that has as its parameters the external dependencies required by the class.
- <!-- more -->
- There are several benefits to this particular method of injection; the most obvious is that in a well designed system the dependencies of a class are clearly visible in the constructor. In the <a href="http://blog.efvincent.com/practical-di-101">DI 101</a> post a data provider was defined like this:</p>
- <div><table class="CodeRay"><tr>
- <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
- <a href="#n2" name="n2">2</a>
- <a href="#n3" name="n3">3</a>
- <a href="#n4" name="n4">4</a>
- <a href="#n5" name="n5">5</a>
- <a href="#n6" name="n6">6</a>
- <a href="#n7" name="n7">7</a>
- <a href="#n8" name="n8">8</a>
- <a href="#n9" name="n9">9</a>
- <strong><a href="#n10" name="n10">10</a></strong>
- <a href="#n11" name="n11">11</a>
- <a href="#n12" name="n12">12</a>
- <a href="#n13" name="n13">13</a>
- <a href="#n14" name="n14">14</a>
- </pre></td>
- <td class="code"><pre><span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
- <span class="directive">private</span> readonly IIdentService _identService;
- <span class="directive">private</span> readonly ILogService _logSvc;
- <span class="directive">private</span> <span class="directive">static</span> readonly <span class="predefined-type">List</span><Employee> EmployeeStore = <span class="keyword">new</span> <span class="predefined-type">List</span><Employee>();
- <span class="directive">public</span> DevDataProvider(IIdentService identService, ILogService logSvc) {
- <span class="keyword">if</span> (identService == <span class="predefined-constant">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> ArgumentNullException(<span class="string"><span class="delimiter">"</span><span class="content">identService</span><span class="delimiter">"</span></span>);
- <span class="keyword">if</span> (logSvc == <span class="predefined-constant">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> ArgumentNullException(<span class="string"><span class="delimiter">"</span><span class="content">logSvc</span><span class="delimiter">"</span></span>);
- _identService = identService;
- _logSvc = logSvc;
- }
- <span class="comment">// Remaining implementation omitted for brevity</span>
- }
- </pre></td>
- </tr></table>
- </div>
- <p>The constructor is on line 6. From this constructor we can see that the DevDataProvider has dependencies on an IIdentityService and an ILogService. There should be no other dependencies in the class other than to well known, stable libraries like the <a href="http://msdn.microsoft.com/en-us/library/hfa3fa08.aspx">BCL</a>.</p>
- <p>There are other advantages to using constructor injection. Should the list of dependencies get too long, say longer than four parameters, you’ve got a code smell that perhaps the class is doing too much, violating the single responsibility principal.</p>
- <h2 id="bootstrapping">Bootstrapping</h2>
- <p>In order to be able to resolve dependencies, the DI container must be configured. This set up is done during the <strong>bootstrapping</strong> phase. Typically this only needs to be done once, but changes to the container make sense in some scenarios like when a DI container is being used to support extensions or plug-ins. In that case components might be added or removed from the DI container while the app is running. These scenarios are out of scope for this post.</p>
- <p>The container may be configured in several ways – Auto configuring, configuration in code, and configuration files (typically XML / app or web.config files). My current favorite DI framework is AutoFac, and I typically configure in code, but different projects will have different demands, so familiarize yourself with the specifics of your selected framework and understand the tradeoffs involved in the different types of configuration. You can even configure the DI container using more than one method – perhaps Auto configuring for the bulk of the registrations, then code or XML for more specific configuration needs.</p>
- <h2 id="bootstrapping-a-console-application">Bootstrapping a Console Application</h2>
- <p>Depending on the type of application you’re working on, there are specific places for bootstrapping to take place. The <em>place</em> to do configuration and bootstrapping is sometimes referred to as the <strong>composition root</strong> <em>(you can read about these concepts in more detail in <a href="http://www.manning.com/seemann/">Mark Seeman’s Dependency Injection</a> book, published by Manning)</em>.</p>
- <p>In a console application, the static Main() method is a typical place to configure the container. While we rarely write console apps in production (at least I rarely do), the simplicity makes it easy to see the implications of the bootstrapping procedure.</p>
- <p>In the following sequence diagram, in step one [1] the Main() entry point is called on the console application. Main() is serving as the composition root. From there a private Bootstrap() methods is called [2] and the DI container is configured. The exact mechanism varies by framework.</p>
- <p><a href="http://blog.efvincent.com/wp-content/uploads/2011/06/Capture.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/06/Capture_thumb.png" alt="Capture" /></a></p>
- <p>Once the container is configured, the main entry point requests that the DI container resolve the App type [3]. The DI container creates whatever dependencies are required by the App [4]. This happens hierarchically; dependencies may themselves have dependencies and so on. The DI container sorts all this out and is also responsible for lifetimes of create objects etc. The DI container can create and return the instance off the App [5]. The Main() function can then pass control to the app [6] which will leverage the injected dependencies [7] to do the real work.</p>
- <h2 id="only-directly-reference-the-di-container-in-the-bootstrapper">Only Directly Reference the DI Container in the Bootstrapper</h2>
- <p>This is an important point, and if you get nothing else from this post, understand this.</p>
- <ul>
- <li>The DI container is configured in the composition root (Main() in this case)</li>
- <li>The DI container is used to resolve or build the App</li>
- <li>The app is then run to do the work</li>
- </ul>
- <p>Once the app is instantiated, it should have all of its dependencies injected. <strong>The app should not have a reference to the DI container!</strong> If we allow the app or any of its dependencies to have access to the container, then several bad things happen:</p>
- <h4 id="weve-taken-on-a-dependency-to-the-di-container-itself">We’ve taken on a dependency to the DI Container itself</h4>
- <p>Yes its true that the assembly has a dependency on the DI container. But for purposes of this discussion the assembly is not the application. The App class and the services (other classes) it depends on is the application. We don’t want to take a dependency on the DI container in those classes; rather, we should be able to switch to a different DI container if needed and not effect the App and the dependent services.</p>
- <p>In any kind of a significant application the app’s classes would be in a different assembly, and services might be scattered across even more assemblies, and those should not have a dependency on a DI container. They should however be designed and built with the DI pattern in mind – with the dependencies specified in the constructor, with references to abstract types or interfaces, rather than to concrete implementations.</p>
- <h4 id="were-hiding-a-dependency-inside-the-app">We’re hiding a dependency inside the App</h4>
- <p>Earlier I mentioned that a benefit of constructor injection is that the dependencies are clearly visible (even <em>documented</em> if you will) in the signature of the constructor. We really don’t want to see lines like this buried in the methods of the classes:</p>
- <div><table class="CodeRay"><tr>
- <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
- <a href="#n2" name="n2">2</a>
- <a href="#n3" name="n3">3</a>
- <a href="#n4" name="n4">4</a>
- <a href="#n5" name="n5">5</a>
- <a href="#n6" name="n6">6</a>
- <a href="#n7" name="n7">7</a>
- <a href="#n8" name="n8">8</a>
- </pre></td>
- <td class="code"><pre><span class="comment">// Anti-pattern - don't use DI container except</span>
- <span class="comment">// in composition root</span>
- var dal = <span class="predefined-type">Container</span>.Resolve<IDataAccessService>();
- <span class="comment">// And defintely don't do this</span>
- var dal = <span class="keyword">new</span> SqlDataAccessService(connectString);
- </pre></td>
- </tr></table>
- </div>
- <p>A class that that has these lines buried inside somewhere has hidden dependencies on both the DI container and IDataAccessService (or worse, by using the new keyword directly, on the SqlDataAccessService). These hidden dependencies undermine the benefits of using DI containers at all.</p>
- <h3 id="bootstrapping-in-other-application-types">Bootstrapping in other Application Types</h3>
- <p>Other types of apps have different places for bootstrapping and application roots. Unlike a console app, an ASP.NET MVC 3 application isn’t top-down linear, the application must respond to web requests. It does so by creating instances of controllers, and calling methods on those controllers to respond to web requests.</p>
- <p>A controller in MVC3 is like the app was in our console example above. It will be resolved, or created, by the DI container. Controllers are different in that there will likely be several different controllers in an MVC application. Also, we don’t get to resolve a controller and tell it to run right from the composition root, the ASP.NET MVC framework will be receiving web requests and will need to resolve controllers later, after bootstrapping.</p>
- <p>In ASP.NET MVC 3 this is accomplished by providing a <em>hook</em>, or a place where we can supply a DI container for ASP.NET MVC 3 to use when creating controllers. The developer configures the DI container, and then wires that container into the MVC framework via an instance of IControllerActivator. In the case of AutoFac, there’s a <a href="http://nuget.org/List/Packages/Autofac.Mvc3">NuGet package called AutoFac.Mvc3</a> that includes classes to integrate with MVC3. The implementation details are beyond the scope of this post – just <a href="http://duckduckgo.com/">DuckDuckGo</a> AutoFac.Mvc and find a wealth of additional detail. Same goes for WCF, WPF, and Silverlight applications. There are best practices for configuring DI containers for each app type.</p>
- <h3 id="di-unfriendly-application-types">DI Unfriendly Application Types</h3>
- <p>Some application types just do not lend themselves very easily to dependency injection patterns. Classic ASP.NET pops into mind immediately. It was written before Microsoft was as willing to accept OSS, community driven concepts such as DI Containers. A big red flag with ASP.NET is that all subclasses to the Page class (which is what all your ASP.NET pages are) must have a parameterless default constructor. Well there goes parameter injection!</p>
- <p>There are other mechanisms for implementing DI patterns in this case, but they’re sub-optimal. Again I’d refer you to <a href="http://www.manning.com/seemann/">Mark Seeman’s Dependency Injection</a> book, which is far and away the best DI book in the .NET space, for advice and examples in dealing with DI unfriendly application types.</p>
- <h3 id="in-summary">In Summary</h3>
- <p>Hopefully this was helpful in your understanding of a couple of key aspects of using DI containers. Practice a few console applications, and write some tests too. Once you get the idea, move on to more interesting application types. Before long you’ll be shocked you ever wrote applications <em>without</em> some degree of dependency injection. Yea – it’s that good for you.</p>
- ]]></content>
- </entry>
-
- <entry>
- <title type="html"><![CDATA[A Taste of Dependency Injection, Testing, and Mocking]]></title>
- <link href="http://efvincent.github.io/blog/2011/05/27/di-mock/"/>
- <updated>2011-05-27T20:28:53-04:00</updated>
- <id>http://efvincent.github.io/blog/2011/05/27/di-mock</id>
- <content type="html"><![CDATA[<p><a href="http://blog.efvincent.com/practical-di-101">My last post</a> provided a brief introduction into dependency injection. To review, the example included a data provider for Employee objects, which included a feature to return the object corresponding to the currently logged in user. In the end the following interfaces were defined:</p>
- <p><strong>IDataProvider</strong> – the function is obvious from the name. One implementation, the DevDataProvider, uses a static List<employee> as a data store.</employee></p>
- <p><strong>IIdentityService</strong> – describes a service that supplies the <em>current</em> identity. What current is depends on the implementation of course. A concrete WindowsIdentService defines current as the currently logged in Windows user. The TestIdentService implementation always returned the same username, which is useful for testing as we will see.</p>
- <p><strong>ILogService</strong> – describes a simple logging service. The ConsoleLogService implementation prints logs to the console.</p>
- <!-- more -->
- <p>### Dependency Injection &Testing</p>
- <p>For this post I’ve added a standard MSTest project and a couple of tests for the data provider. The use of dependency injection patterns in the design of this simple example allows us to easily isolate the code under test.</p>
- <div><table class="CodeRay"><tr>
- <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
- <a href="#n2" name="n2">2</a>
- <a href="#n3" name="n3">3</a>
- <a href="#n4" name="n4">4</a>
- <a href="#n5" name="n5">5</a>
- <a href="#n6" name="n6">6</a>
- <a href="#n7" name="n7">7</a>
- <a href="#n8" name="n8">8</a>
- <a href="#n9" name="n9">9</a>
- <strong><a href="#n10" name="n10">10</a></strong>
- <a href="#n11" name="n11">11</a>
- <a href="#n12" name="n12">12</a>
- <a href="#n13" name="n13">13</a>
- <a href="#n14" name="n14">14</a>
- </pre></td>
- <td class="code"><pre><span class="directive">static</span> IContainer afContainer;
- [ClassInitialize]
- <span class="directive">public</span> <span class="directive">static</span> <span class="type">void</span> TestInit(TestContext ctx) {
- var idSvc = A.Fake<IIdentService>();
- A.CallTo(() => idSvc.GetCurrentUserName())
- .Returns(<span class="string"><span class="delimiter">"</span><span class="content">FAKE-ID</span><span class="delimiter">"</span></span>);
- var bldr = <span class="keyword">new</span> ContainerBuilder();
- bldr.RegisterInstance(idSvc);
- bldr.RegisterInstance(A.Fake<ILogService>());
- bldr.RegisterType<DevDataProvider>().As<IDataProvider>();
- afContainer = bldr.Build();
- }
- </pre></td>
- </tr></table>
- </div>
- <p>The test class has a static DI container instance, initialized in the class initializer. I’m using <a href="http://code.google.com/p/fakeiteasy/">FakeItEasy</a> to create a fake IIdentService at line five. Like six tells the FakeItEasy framework what to return when the GetCurrentUserName() method is called on the fake ident service. Having a fixed response makes testing the data provider a piece of cake.</p>
- <p>I then register the fake ident service as well as a fake log service. For the log service, we don’t need to specify any behavior for the methods. The FakeItEasy framework will effectively sink any calls to the methods of the fake log service, which is fine for this test.</p>
- <p>Lastly the data provider we want to test is registered with the DI container builder, and then container is built. The tests go on to use the DI container to resolve an instance of the data provider. The DI container will configure the data provider’s dependencies for a log service and an identity service with the fakes we built.</p>
- <div><table class="CodeRay"><tr>
- <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
- <a href="#n2" name="n2">2</a>
- <a href="#n3" name="n3">3</a>
- <a href="#n4" name="n4">4</a>
- <a href="#n5" name="n5">5</a>
- <a href="#n6" name="n6">6</a>
- <a href="#n7" name="n7">7</a>
- <a href="#n8" name="n8">8</a>
- </pre></td>
- <td class="code"><pre>[TestMethod()]
- <span class="directive">public</span> <span class="type">void</span> GetCurrentEmployeeTest() {
- var e = <span class="keyword">new</span> Employee { WindowsUsername = <span class="string"><span class="delimiter">"</span><span class="content">FAKE-ID</span><span class="delimiter">"</span></span> };
- var dal = afContainer.Resolve<IDataProvider>();
- dal.AddEmployee(e);
- var result = dal.GetCurrentEmployee();
- Assert.AreEqual(e.WindowsUsername, result.WindowsUsername);
- }
- </pre></td>
- </tr></table>
- </div>
- <p>This is just a small example of using a DI container in combination with a mock / fake framework for testing. The AutoFac DI container can handle much more complex scenarios than what we’ve thrown at it here. The same is true for the FakeItEasy component. Both of these components are well used, well maintained open source projects. You can find lots of documentation and examples for both. Or you can use any number of other DI containers and mocking frameworks to achieve equivalent results.</p>
- <p>The source code for the example is available <a href="https://bitbucket.org/efvincent/blog-post-dependency-injection-101">here</a>, and the blog entry the precedes this one is available <a href="http://blog.efvincent.com/practical-di-101/">here</a>.</p>
- ]]></content>
- </entry>
-
- <entry>
- <title type="html"><![CDATA[Practical Dependency Injection 101]]></title>
- <link href="http://efvincent.github.io/blog/2011/05/27/practical-di-101/"/>
- <updated>2011-05-27T13:08:27-04:00</updated>
- <id>http://efvincent.github.io/blog/2011/05/27/practical-di-101</id>
- <content type="html"><![CDATA[<p>In this post we take a look at dependency injection (DI). Target audience is competent .NET developers, C# specifically (but VB’ers who read C# can benefit just as much), who’ve heard of DI but haven’t gotten around to figuring out how it fits in their day to day.</p>
- <!-- more -->
- <p>### What is Dependency Injection</p>
- <p>The first question that we need to address is: What is it that DI does for us? What problem is being solved? DI is about coupling; the degree to which program unit refers to other units. In .NET the units we’re typically worried about are classes, interfaces, components, and assemblies. Dependency injection facilitates reduction these interdependencies. Are DI patterns a silver bullet? Of course not. You can always write bad code regardless of patterns. That being said, if you’re already writing decent code and have good fundamentals, but are not using DI patterns, you’ve got the opportunity to take a leap forward.</p>
- <p>How does DI reduce help reduce coupling? The easiest way to describe it is by diving directly into an example.</p>
- <h3 id="example-scenario">Example Scenario</h3>
- <p>We’ll work on a hypothetical in-house app where the Windows AD authenticates employees, and their Windows username is used to index a database with Employee information. It’s pretty common to see stuff like this happening in-house with line of business applications.</p>
- <p>The example uses a provider pattern – all the data access will go through a data access provider, allowing us to build a simple provider that stores records in memory during this, our prototype phase. Theoretically we’d replace this as development continued with a provider that leverages persistent storage later.</p>
- <p>Here’s the base level example program with no consideration for dependency injection:</p>
- <div><table class="CodeRay"><tr>
- <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
- <a href="#n2" name="n2">2</a>
- <a href="#n3" name="n3">3</a>
- <a href="#n4" name="n4">4</a>
- <a href="#n5" name="n5">5</a>
- <a href="#n6" name="n6">6</a>
- <a href="#n7" name="n7">7</a>
- <a href="#n8" name="n8">8</a>
- <a href="#n9" name="n9">9</a>
- <strong><a href="#n10" name="n10">10</a></strong>
- <a href="#n11" name="n11">11</a>
- <a href="#n12" name="n12">12</a>
- <a href="#n13" name="n13">13</a>
- <a href="#n14" name="n14">14</a>
- <a href="#n15" name="n15">15</a>
- <a href="#n16" name="n16">16</a>
- <a href="#n17" name="n17">17</a>
- <a href="#n18" name="n18">18</a>
- <a href="#n19" name="n19">19</a>
- <strong><a href="#n20" name="n20">20</a></strong>
- <a href="#n21" name="n21">21</a>
- <a href="#n22" name="n22">22</a>
- <a href="#n23" name="n23">23</a>
- <a href="#n24" name="n24">24</a>
- <a href="#n25" name="n25">25</a>
- <a href="#n26" name="n26">26</a>
- <a href="#n27" name="n27">27</a>
- <a href="#n28" name="n28">28</a>
- <a href="#n29" name="n29">29</a>
- <strong><a href="#n30" name="n30">30</a></strong>
- <a href="#n31" name="n31">31</a>
- <a href="#n32" name="n32">32</a>
- <a href="#n33" name="n33">33</a>
- <a href="#n34" name="n34">34</a>
- <a href="#n35" name="n35">35</a>
- <a href="#n36" name="n36">36</a>
- <a href="#n37" name="n37">37</a>
- <a href="#n38" name="n38">38</a>
- <a href="#n39" name="n39">39</a>
- <strong><a href="#n40" name="n40">40</a></strong>
- <a href="#n41" name="n41">41</a>
- <a href="#n42" name="n42">42</a>
- <a href="#n43" name="n43">43</a>
- <a href="#n44" name="n44">44</a>
- <a href="#n45" name="n45">45</a>
- <a href="#n46" name="n46">46</a>
- <a href="#n47" name="n47">47</a>
- <a href="#n48" name="n48">48</a>
- <a href="#n49" name="n49">49</a>
- <strong><a href="#n50" name="n50">50</a></strong>
- <a href="#n51" name="n51">51</a>
- <a href="#n52" name="n52">52</a>
- <a href="#n53" name="n53">53</a>
- <a href="#n54" name="n54">54</a>
- <a href="#n55" name="n55">55</a>
- <a href="#n56" name="n56">56</a>
- <a href="#n57" name="n57">57</a>
- <a href="#n58" name="n58">58</a>
- <a href="#n59" name="n59">59</a>
- <strong><a href="#n60" name="n60">60</a></strong>
- <a href="#n61" name="n61">61</a>
- </pre></td>
- <td class="code"><pre><span class="type">class</span> <span class="class">Program</span> {
- <span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
- <span class="comment">// ** Without using an DI Container approach **</span>
- <span class="comment">// Create a new provider aka data access layer</span>
- var dal = <span class="keyword">new</span> DevDataProvider();
- <span class="comment">// New up an employee that's supposed to represent the currently logged in user</span>
- var e = <span class="keyword">new</span> Employee() {
- WindowsUsername = <span class="string"><span class="delimiter">"</span><span class="content">thanos</span><span class="char">\\</span><span class="content">efvincent</span><span class="delimiter">"</span></span>,
- EmployeeId = <span class="string"><span class="delimiter">"</span><span class="content">0001</span><span class="delimiter">"</span></span>,
- FName = <span class="string"><span class="delimiter">"</span><span class="content">Eric</span><span class="delimiter">"</span></span>,
- LName = <span class="string"><span class="delimiter">"</span><span class="content">Vincent</span><span class="delimiter">"</span></span>
- };
- <span class="comment">// Add it to the data access layer</span>
- dal.AddEmployee(e);
- <span class="comment">// See if the dal can find the current user</span>
- e = dal.GetCurrentEmployee();
- Console.WriteLine(
- <span class="string"><span class="delimiter">"</span><span class="content">Current logged in person is: {0}</span><span class="delimiter">"</span></span>, e == <span class="predefined-constant">null</span> ? <span class="string"><span class="delimiter">"</span><span class="content">unknown</span><span class="delimiter">"</span></span> : e.FName);
- <span class="comment">// End</span>
- Console.Write(<span class="string"><span class="delimiter">"</span><span class="content">Press any key...</span><span class="delimiter">"</span></span>);
- Console.ReadKey(<span class="predefined-constant">true</span>);
- }
- }
- <span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> {
- <span class="directive">private</span> <span class="directive">static</span> readonly <span class="predefined-type">List</span><Employee> EmployeeStore = <span class="keyword">new</span> <span class="predefined-type">List</span><Employee>();
- <span class="directive">public</span> Employee GetCurrentEmployee() {
- var emp = EmployeeStore.FirstOrDefault(
- e => e.WindowsUsername.Equals(GetCurrentUserName(), StringComparison.OrdinalIgnoreCase));
- <span class="keyword">return</span> emp;
- }
- <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
- EmployeeStore.Add(e);
- }
- <span class="directive">public</span> IQueryable<Employee> Employees() {
- <span class="keyword">return</span> EmployeeStore.AsQueryable();
- }
- <span class="directive">private</span> <span class="directive">static</span> string GetCurrentUserName() {
- var wu = WindowsIdentity.GetCurrent();
- <span class="keyword">return</span> wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
- }
- }
- <span class="directive">public</span> <span class="type">class</span> <span class="class">Employee</span> {
- <span class="directive">public</span> string WindowsUsername { get; set; }
- <span class="directive">public</span> string EmployeeId { get; set; }
- <span class="directive">public</span> string FName { get; set; }
- <span class="directive">public</span> string LName { get; set; }
- }
- </pre></td>
- </tr></table>
- </div>
- <p>In Main() we new up the data access layer, create a new employee, and add it to our store using the data access layer. At line 21 we ask the data access layer to retrieve the employee record for the currently logged in user. Looks pretty typical, so how can IoC help? Let’s look at the coupling here – what classes are dependent on what other classes?</p>
- <p><a href="http://blog.efvincent.com/wp-content/uploads/2011/05/image.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/05/image_thumb.png" alt="image" /></a></p>
- <p>Our main program depends on the DevDataProvider class, and that depends on System.Security to find the Windows username of the currently logged in user. Asking the data access layer to determine the currently logged in user isn’t the best idea, but this is blog post code created to check out dependency injection, so deal with that for the moment.</p>
- <p>Why are these dependencies undesirable? First consider how flexible this software is. Or rather, inflexible. We created a “quick” DevDataProvider that stores stuff in a static list. As we continue to build a system, we’d have to refer to DevDataProvider from more and more classes, creating a brittle, tightly coupled system. Replacing DevDataProvider becomes more of a maintenance problem.</p>
- <p>Next think about testability. In real life there are unit tests (there should be anyway). One reason why people find excuses not to unit test is because their code is difficult to test. In this example, if we want to test DevDataProvider.GetCurrentEmployee() we have to consider that under the covers it’s calling the Windows API to get the current username. This makes that method harder to than it needs to be.</p>
- <h3 id="step-one--leveraging-interfaces">Step One – Leveraging Interfaces</h3>
- <p>In this version, we’ve factored out an interface called IDataProvider, and one called IIdentService. The IDataProvider should be pretty obvious – but IIdentService? The idea here is to decouple from the Windows API itself. A developer should understand <em>everywhere _that the application makes contact with _any</em> external modules, including the operating system, and then consider what the repercussions of that contact are. In this example, coupling to the Windows API to get then logged in username so directly is undesirable. We want to use a <em>service</em> that would supply us with credentials. That way if we’re testing, we can create a fake service that provides a predictable answer, and is therefore easier to test.</p>
- <p>Coding to an interface also allows us to radically change the behavior of the service without having to alter its dependencies. If we move to a ASP.NET environment for example, we won’t want to use the current Windows Identity, we may want to use user information from the http context.</p>
- <div><table class="CodeRay"><tr>
- <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
- <a href="#n2" name="n2">2</a>
- <a href="#n3" name="n3">3</a>
- <a href="#n4" name="n4">4</a>
- <a href="#n5" name="n5">5</a>
- <a href="#n6" name="n6">6</a>
- <a href="#n7" name="n7">7</a>
- <a href="#n8" name="n8">8</a>
- <a href="#n9" name="n9">9</a>
- <strong><a href="#n10" name="n10">10</a></strong>
- <a href="#n11" name="n11">11</a>
- <a href="#n12" name="n12">12</a>
- <a href="#n13" name="n13">13</a>
- <a href="#n14" name="n14">14</a>
- <a href="#n15" name="n15">15</a>
- <a href="#n16" name="n16">16</a>
- <a href="#n17" name="n17">17</a>
- <a href="#n18" name="n18">18</a>
- <a href="#n19" name="n19">19</a>
- <strong><a href="#n20" name="n20">20</a></strong>
- <a href="#n21" name="n21">21</a>
- <a href="#n22" name="n22">22</a>
- <a href="#n23" name="n23">23</a>
- <a href="#n24" name="n24">24</a>
- <a href="#n25" name="n25">25</a>
- <a href="#n26" name="n26">26</a>
- <a href="#n27" name="n27">27</a>
- <a href="#n28" name="n28">28</a>
- <a href="#n29" name="n29">29</a>
- <strong><a href="#n30" name="n30">30</a></strong>
- <a href="#n31" name="n31">31</a>
- <a href="#n32" name="n32">32</a>
- <a href="#n33" name="n33">33</a>
- <a href="#n34" name="n34">34</a>
- <a href="#n35" name="n35">35</a>
- <a href="#n36" name="n36">36</a>
- <a href="#n37" name="n37">37</a>
- <a href="#n38" name="n38">38</a>
- <a href="#n39" name="n39">39</a>
- <strong><a href="#n40" name="n40">40</a></strong>
- <a href="#n41" name="n41">41</a>
- <a href="#n42" name="n42">42</a>
- <a href="#n43" name="n43">43</a>
- <a href="#n44" name="n44">44</a>
- <a href="#n45" name="n45">45</a>
- <a href="#n46" name="n46">46</a>
- <a href="#n47" name="n47">47</a>
- </pre></td>
- <td class="code"><pre><span class="comment">// Interface defining an identity service</span>
- <span class="directive">public</span> <span class="type">interface</span> <span class="class">IIdentService</span> {
- string GetCurrentUserName();
- }
- <span class="comment">// Implementation of an identity service that returns the current</span>
- <span class="comment">// logged in windows username</span>
- <span class="directive">public</span> <span class="type">class</span> <span class="class">WindowsIdentService</span> : IIdentService {
- <span class="directive">public</span> string GetCurrentUserName() {
- var wu = WindowsIdentity.GetCurrent();
- <span class="keyword">return</span> wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
- }
- }
- <span class="comment">// Interface defining a data provider service</span>
- <span class="directive">public</span> <span class="type">interface</span> <span clas…
Large files files are truncated, but you can click here to view the full file