PageRenderTime 69ms CodeModel.GetById 15ms app.highlight 21ms RepoModel.GetById 1ms app.codeStats 4ms

/atom.xml

https://github.com/efvincent/efvincent.github.io
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

  1<?xml version="1.0" encoding="utf-8"?>
  2<feed xmlns="http://www.w3.org/2005/Atom">
  3
  4  <title><![CDATA[Curried Functions]]></title>
  5  <link href="http://efvincent.github.io/atom.xml" rel="self"/>
  6  <link href="http://efvincent.github.io/"/>
  7  <updated>2014-08-18T13:03:44-04:00</updated>
  8  <id>http://efvincent.github.io/</id>
  9  <author>
 10    <name><![CDATA[Eric F. Vincent]]></name>
 11    
 12  </author>
 13  <generator uri="http://octopress.org/">Octopress</generator>
 14
 15  
 16  <entry>
 17    <title type="html"><![CDATA[Debounce as a Directive]]></title>
 18    <link href="http://efvincent.github.io/blog/2014/08/18/debounce-as-a-directive/"/>
 19    <updated>2014-08-18T01:28:33-04:00</updated>
 20    <id>http://efvincent.github.io/blog/2014/08/18/debounce-as-a-directive</id>
 21    <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
 22so that the handler would not be called more than every X milliseconds. His app was doing
 23the fairly typical chore of searching through a long list as the user types into a
 24search box. Firing a <code>digest</code> (that’s Angular’s re-bind and re-render loop) for each
 25keystroke causes a jumpy, jittery refresh storm.</p>
 26
 27<p>What he was looking for is commonly referred to as to <em>debounce</em> or <em>throttle</em> a
 28function. There are many implementations around, but his question was specifically
 29about debounce in the context of Angular, preferably as a directive.</p>
 30
 31<!-- more -->
 32
 33<p>I found a snippet authored by <a href="http://tommaitland.net">Tom Maitland</a> that does just
 34what we need. I tweaked it slightly (also as a <a href="https://gist.github.com/efvincent/9784923">Gist</a>
 35and <a href="http://jsfiddle.net/efvincent/vkphp2fa/">JSFiddle</a>):</p>
 36
 37<div><table class="CodeRay"><tr>
 38  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 39<a href="#n2" name="n2">2</a>
 40<a href="#n3" name="n3">3</a>
 41<a href="#n4" name="n4">4</a>
 42<a href="#n5" name="n5">5</a>
 43<a href="#n6" name="n6">6</a>
 44<a href="#n7" name="n7">7</a>
 45<a href="#n8" name="n8">8</a>
 46<a href="#n9" name="n9">9</a>
 47<strong><a href="#n10" name="n10">10</a></strong>
 48<a href="#n11" name="n11">11</a>
 49<a href="#n12" name="n12">12</a>
 50<a href="#n13" name="n13">13</a>
 51<a href="#n14" name="n14">14</a>
 52<a href="#n15" name="n15">15</a>
 53<a href="#n16" name="n16">16</a>
 54<a href="#n17" name="n17">17</a>
 55<a href="#n18" name="n18">18</a>
 56<a href="#n19" name="n19">19</a>
 57<strong><a href="#n20" name="n20">20</a></strong>
 58<a href="#n21" name="n21">21</a>
 59<a href="#n22" name="n22">22</a>
 60<a href="#n23" name="n23">23</a>
 61<a href="#n24" name="n24">24</a>
 62<a href="#n25" name="n25">25</a>
 63<a href="#n26" name="n26">26</a>
 64</pre></td>
 65  <td class="code"><pre><span class="comment">// Defines the module as &quot;app&quot;, this is not best practice for module</span>
 66<span class="comment">// definition or project structure, focus on the directive</span>
 67angular.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>) {
 68  <span class="keyword">return</span> {
 69    <span class="key">restrict</span>: <span class="string"><span class="delimiter">'</span><span class="content">A</span><span class="delimiter">'</span></span>,
 70    <span class="key">require</span>: <span class="string"><span class="delimiter">'</span><span class="content">ngModel</span><span class="delimiter">'</span></span>,
 71    <span class="key">priority</span>: <span class="integer">99</span>,
 72    <span class="function">link</span>: <span class="keyword">function</span>(scope, elm, attr, ngModelCtrl) {
 73      <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>;
 74
 75      elm.unbind(<span class="string"><span class="delimiter">'</span><span class="content">input</span><span class="delimiter">'</span></span>);
 76
 77      <span class="keyword">var</span> debounce;
 78      elm.bind(<span class="string"><span class="delimiter">'</span><span class="content">input</span><span class="delimiter">'</span></span>, <span class="keyword">function</span>() {
 79        <span class="predefined">$timeout</span>.cancel(debounce);
 80          ngModelCtrl.<span class="predefined">$setViewValue</span>(elm.val());
 81        }, attr.tlDebounce || <span class="integer">1000</span>);
 82      });
 83      elm.bind(<span class="string"><span class="delimiter">'</span><span class="content">blur</span><span class="delimiter">'</span></span>, <span class="keyword">function</span>() {
 84        scope.<span class="predefined">$apply</span>(<span class="keyword">function</span>() {
 85          ngModelCtrl.<span class="predefined">$setViewValue</span>(elm.val());
 86        });
 87      });
 88    }
 89  }
 90});
 91</pre></td>
 92</tr></table>
 93</div>
 94
 95<h2 id="examining-the-directive">Examining the directive</h2>
 96
 97<p>The directive starts at line 3 by defining a module and calling the <code>directive</code> function
 98which causes Angular to register a directive in that module. This directive is called <code>tlBounce</code>.
 99To define a directive we pass a function and our function returns a directive definition object.</p>
100
101<h3 id="injecting-angulars-timer-service">Injecting Angular’s Timer service</h3>
102
103<p>The debounce directive will use a timer to assure that when attached to a text box, the underlying
104model will only be updated every X milliseconds. We’ll see the algorithm in a bit.</p>
105
106<p>When Angular needs an instance of our directive, it will call the function we’ve provided. Angular
107will inspect the function and detect that it has a dependency; to call the function Angular must
108provide, or <em>inject</em> something called <code>$timeout</code>, which is one of Angular’s services. Angular offers
109many <em>services</em> to you as the application developer to use in creating a directive (or factory,
110filter, controller, or the other Angular things). These services are objects or functions provided by the framework.</p>
111
112<p>The tip-off that <code>$timeout</code> is a service is the leading dollar sign. Angular will use its
113<a href="https://docs.angularjs.org/api/auto/service/$injector#!">Injector</a> service to find a <code>$timeout</code> and pass it
114to us. We’ll then use the <code>$timeout</code> in our <em>link function</em>.</p>
115
116<h3 id="the-link-function">The link function</h3>
117
118<p>Without getting into the guts of directive development, suffice it to say that in most
119cases when writing a directive you’ll want to focus on the <code>link</code> function. For more information
120on the link function, there’s the <a href="http://angularjs.org/">Angular Docs</a>, and another good source of information is
121<a href="http://www.angularjshub.com/examples/customdirectives/compilelinkfunctions/">AngularJS Hub</a>.</p>
122
123<p>The <code>link</code> function sets up each instance of the directive. You supply the function that can have
124up to four parameters. <code>link: function(scope, elm, attr, ngModelCtrl)</code>.</p>
125
126<h4 id="link-function-parameters">Link function parameters</h4>
127
128<p>The first is the directive’s local scope, which is usually used like you use scope in a controller
129to maintain and bind to the internal state of the directive. We’ll see how <code>scope</code> is used here in a second.</p>
130
131<p>Second is the <code>elm</code> or <em>element</em> parameter. This is the DOM element that the directive to which the
132directive is attached. For debounce, the directive is attached to an input, usually a text box. You can do the
133usual DOM-stuff to the element, attach event handlers, change content, add children, etc. AAMOF you actually
134have an Angular wrapper around the element, so you get some additional JQuery like functions on the element.</p>
135
136<p>Third is <code>attr</code>, the attributes. This is a map of the attributes on the element to which our directive is
137attached. In our case, we’re using the <code>attr</code> to detect if we’re attached to a radio button or check box; our
138deBounce doesn’t have a meaning for those controllers, so we bail if we see that we’re attached to one (line 9).</p>
139
140<p>Lastly is the <code>ngModelCtrl</code>, which is the least intuitive. This is a controller requirement of our directive,
141it says that any directive we’re attached to needs to have an <code>ngModelCtrl</code> controller. This sort of limits
142our deBouncer, but the target use case is to put this directive on a text box that’s using AngularJS’s binding.</p>
143
144<h3 id="debounce-algorithm">DeBounce Algorithm</h3>
145
146<p>The strategy is as follows:</p>
147
148<ol>
149  <li>Detach the input handler (line 11) that usually updates the model</li>
150  <li>Bind a new input handler
151    <ol>
152      <li>Cancel any pending debounce timer (line 15)</li>
153      <li>Set up a new debounce timer
154        <ol>
155          <li>It should go off in the time specified by the <code>tl-debounce</code> attribute, or 1,000ms if the attribute is
156 not specified (line 18).</li>
157        </ol>
158      </li>
159      <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>
160    </ol>
161  </li>
162  <li>Bind a new blur handler, so when th user leaves the field the model is always updated.
163    <ol>
164      <li>Put the call to <code>$setNewValue()</code> inside a <code>scope.apply()</code> so the change causes a digest (Angular rebinds everything).</li>
165    </ol>
166  </li>
167</ol>
168
169<h3 id="the-digest">The Digest</h3>
170<p>One important point - you may be thinking that you could have used the standard JavaScript timer. Why
171use Angular’s <code>$timer</code> service? It’s because Angular needs to know when the model changes so that it
172can perform it’s two way binding / model-view synchronization. By using Angular’s timer, you can be assured
173that Angular will know when the timer goes off and will do all the right Angular binding stuff at that time.</p>
174
175<h3 id="but-eric-youre-wrong-and-oh-so-stupid">But Eric, you’re wrong and oh so stupid!</h3>
176<blockquote>
177  <p>You <strong>could</strong> use the normal timer, because when you call <code>.$setViewValue()</code>
178you’re letting Angular know something needs to change, right? I mean, it starts in a dollar sign,
179so it’s all Angulary, right?  </p>
180</blockquote>
181
182<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
183fifteen minutes, then look up the docs, then unleash a stream of profanities. It happens that <code>.$setViewValue()</code> does
184<strong>not</strong> cause a digest, probably because of performance or some other really good reason. Doesn’t make it fun though, and
185it’s the kind of undiscoverable crap that qualifies as a legit complaint about AngularJS. Take your medicine.</p>
186
187<p>So that’s DeBounce - it actually works pretty well for things like text boxes that do searches and stuff like that.
188I use it in production, but there’s no warrentee so YMMV. Have a good one…</p>
189
190<p>-e</p>
191]]></content>
192  </entry>
193  
194  <entry>
195    <title type="html"><![CDATA[GitHubify(Blog)]]></title>
196    <link href="http://efvincent.github.io/blog/2014/08/15/Octopress-github-ruby-windows/"/>
197    <updated>2014-08-15T12:00:11-04:00</updated>
198    <id>http://efvincent.github.io/blog/2014/08/15/Octopress-github-ruby-windows</id>
199    <content type="html"><![CDATA[<p>For my shiney new blog I decided to go full hipster and host on GitHub. This means that
200the entire site, source code as well as the blog website itself, can be seen at
201<a href="https://github.com/efvincent/efvincent.github.io">my blog’s repository</a>. Of course all of this will be painfully
202uncool by this time next year. But for the time being it’s fun and the tech is relevant.</p>
203
204<p>Dig in if you want to see the ins and outs of setting all this up on a Windows workstation,
205because Windows is so far out of fashion stuff is starting to not work on it by default. Karma.
206<!--more -->
207## Static Site Generation
208The way GitHub hosted web sites work is that the entire web site is pure static HTML,
209JavaScript, and CSS. If you work in the industry you realize that all the web site
210frameworks (server side) like JSP, ASP.NET, Rails, PHP, etc. all <em>generate</em> pages on
211the fly as the requests come in. This requires a server be running somewhere that can
212run .NET, Java, Ruby, or whatever.</p>
213
214<p>A static site everything is pre-generated, so any server that can respond to requests
215by serving up a file can host a static site. But no one want’s to hand craft HTML pages
216for every blog post. So what you have is a generator; some kind of program that can take
217blog posts written in plain text and <strong>poof!</strong> Generate a static website.</p>
218
219<p>The basic idea is that you have a <em>source</em> directory that has your blog posts written
220in (typically) <a href="https://en.wikipedia.org/wiki/Markdown">markdown</a>, CSS, templates for HTML,
221and the Ruby / JavaScript / whatever that the generator is written in.</p>
222
223<p>There’s typically a command line interface; so you issue the proper command the
224generator takes your markdown and creates a complete, static web site.</p>
225
226<h2 id="github">GitHub</h2>
227<p>That’s where <a href="www.github.com">GitHub</a> comes in. If you don’t know what GitHub is, or
228if you’re completely lost at this point, then you probably need to hit up this
229<a href="https://www.youtube.com/watch?v=oHg5SJYRHA0">everything you need to know to become a modern developer</a>
230tutorial.</p>
231
232<p>Think about it for two seconds, it makes perfect sense. GitHub hosts files in a repository and is a web site.
233So 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
234can serve those web pages up. And that’s all a GitHub hosted static site is. You write posts in
235markdown, you use a generator to create a static site, and you check it into GitHub.</p>
236
237<h2 id="octopress">OctoPress</h2>
238<p>I admittedly don’t have a ton of experience with static site generators. I played with
239a couple before committing to <a href="www.octopress.org">Octopress</a>. At first I wanted to
240use a <a href="http://nodejs.org">Node.js</a> based static site generator. I googled around a bit
241and ended up playing with <a href="https://github.com/jnordberg/wintersmith">Wintersmith</a> for
242a night. It worked, but GitHub makes it easiest to use a Ruby based generator called <a href="http://jekyllrb.com">Jekyll</a>.
243A bit more poking around and I ended up with <a href="www.octopress.org">Octopress</a>, which is
244built on top of Jekyll, offers additional features, and incredibly well written, well
245documented, and easy to use.</p>
246
247<p>When you go to their site you’ll get walked through the installation step by step,
248and there are some nice Ruby build tools available to get things moving, including
249configuring your new Octopress generator to work with GitHub web sites. <strong>Highly recommended</strong></p>
250
251<h2 id="ruby">Ruby</h2>
252<p>Ok so <a href="https://www.youtube.com/watch?v=gBkDvqIGSaE">Ruby hates Windows</a>. It might be passive,
253but the ill feelings are there. Which is fine, everyone can’t love everyone, and Microsoft
254has kinda earned it by being a dick until very recently. But whatever, I’m not with starting
255flame war. It happens that I still use Windows for all kinds of reasons, so I needed to
256get Ruby on my workstation.</p>
257
258<p>Actually I had installed Ruby using <a href="http://chocolatey.org/">Chocolately</a> because I
259love playing with all the languages, but to run Jekyll you’ll need the
260<a href="http://rubyinstaller.org/downloads/">Ruby Development Kit</a>. The RDK is platform
261specific, and is needed to build <em>gems</em> (Ruby packages) that are platform specific,
262which Jekyll either is or depends on indirectly (I didn’t check).</p>
263
264<p>There are <a href="https://github.com/oneclick/rubyinstaller/wiki/Development-Kit">very clear instructions</a>
265that you can follow for getting this set up. Once that’s done you can play along with
266the <a href="www.octopress.org">Octopress</a> setup instructions, which are great. Just follow the
267track that has you deploy to GitHub.</p>
268]]></content>
269  </entry>
270  
271  <entry>
272    <title type="html"><![CDATA[Abandonment Issues]]></title>
273    <link href="http://efvincent.github.io/blog/2014/08/15/abandonment-issues/"/>
274    <updated>2014-08-15T11:52:11-04:00</updated>
275    <id>http://efvincent.github.io/blog/2014/08/15/abandonment-issues</id>
276    <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
277to 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
278for a fresh start.</p>
279
280<p>Expect posts on JavaScript and front end development for a little while. After a career spent designing relational
281databases for finance, insurance and other LOB domains, I’ve been working on SPA style front end enterprise applications for
282a couple of years. And it’s fun. I may actually have a couple of interesting things to say. We’ll see.</p>
283]]></content>
284  </entry>
285  
286  <entry>
287    <title type="html"><![CDATA[DI – Constructor Injection, Bootstrapping]]></title>
288    <link href="http://efvincent.github.io/blog/2011/06/24/di-bootstrap/"/>
289    <updated>2011-06-24T02:07:31-04:00</updated>
290    <id>http://efvincent.github.io/blog/2011/06/24/di-bootstrap</id>
291    <content type="html"><![CDATA[<h2 id="constructor-injection">Constructor Injection</h2>
292<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.
293<!-- more -->
294There 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>
295
296<div><table class="CodeRay"><tr>
297  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
298<a href="#n2" name="n2">2</a>
299<a href="#n3" name="n3">3</a>
300<a href="#n4" name="n4">4</a>
301<a href="#n5" name="n5">5</a>
302<a href="#n6" name="n6">6</a>
303<a href="#n7" name="n7">7</a>
304<a href="#n8" name="n8">8</a>
305<a href="#n9" name="n9">9</a>
306<strong><a href="#n10" name="n10">10</a></strong>
307<a href="#n11" name="n11">11</a>
308<a href="#n12" name="n12">12</a>
309<a href="#n13" name="n13">13</a>
310<a href="#n14" name="n14">14</a>
311</pre></td>
312  <td class="code"><pre><span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
313    <span class="directive">private</span> readonly IIdentService _identService;
314    <span class="directive">private</span> readonly ILogService _logSvc;
315    <span class="directive">private</span> <span class="directive">static</span> readonly <span class="predefined-type">List</span>&lt;Employee&gt; EmployeeStore = <span class="keyword">new</span> <span class="predefined-type">List</span>&lt;Employee&gt;();
316
317    <span class="directive">public</span> DevDataProvider(IIdentService identService, ILogService logSvc) {
318        <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">&quot;</span><span class="content">identService</span><span class="delimiter">&quot;</span></span>);
319        <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">&quot;</span><span class="content">logSvc</span><span class="delimiter">&quot;</span></span>);
320        _identService = identService;
321        _logSvc = logSvc;
322    }
323
324    <span class="comment">// Remaining implementation omitted for brevity</span>
325}
326</pre></td>
327</tr></table>
328</div>
329
330<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>
331
332<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>
333
334<h2 id="bootstrapping">Bootstrapping</h2>
335
336<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>
337
338<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>
339
340<h2 id="bootstrapping-a-console-application">Bootstrapping a Console Application</h2>
341
342<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>
343
344<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>
345
346<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>
347
348<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>
349
350<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>
351
352<h2 id="only-directly-reference-the-di-container-in-the-bootstrapper">Only Directly Reference the DI Container in the Bootstrapper</h2>
353<p>This is an important point, and if you get nothing else from this post, understand this.</p>
354
355<ul>
356  <li>The DI container is configured in the composition root (Main() in this case)</li>
357  <li>The DI container is used to resolve or build the App</li>
358  <li>The app is then run to do the work</li>
359</ul>
360
361<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>
362
363<h4 id="weve-taken-on-a-dependency-to-the-di-container-itself">We’ve taken on a dependency to the DI Container itself</h4>
364
365<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>
366
367<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>
368
369<h4 id="were-hiding-a-dependency-inside-the-app">We’re hiding a dependency inside the App</h4>
370
371<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>
372
373<div><table class="CodeRay"><tr>
374  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
375<a href="#n2" name="n2">2</a>
376<a href="#n3" name="n3">3</a>
377<a href="#n4" name="n4">4</a>
378<a href="#n5" name="n5">5</a>
379<a href="#n6" name="n6">6</a>
380<a href="#n7" name="n7">7</a>
381<a href="#n8" name="n8">8</a>
382</pre></td>
383  <td class="code"><pre><span class="comment">// Anti-pattern - don't use DI container except</span>
384<span class="comment">// in composition root</span>
385
386var dal = <span class="predefined-type">Container</span>.Resolve&lt;IDataAccessService&gt;();
387
388<span class="comment">// And defintely don't do this</span>
389
390var dal = <span class="keyword">new</span> SqlDataAccessService(connectString);
391</pre></td>
392</tr></table>
393</div>
394
395<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>
396
397<h3 id="bootstrapping-in-other-application-types">Bootstrapping in other Application Types</h3>
398
399<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>
400
401<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>
402
403<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>
404
405<h3 id="di-unfriendly-application-types">DI Unfriendly Application Types</h3>
406
407<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>
408
409<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>
410
411<h3 id="in-summary">In Summary</h3>
412
413<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>
414]]></content>
415  </entry>
416  
417  <entry>
418    <title type="html"><![CDATA[A Taste of Dependency Injection, Testing, and Mocking]]></title>
419    <link href="http://efvincent.github.io/blog/2011/05/27/di-mock/"/>
420    <updated>2011-05-27T20:28:53-04:00</updated>
421    <id>http://efvincent.github.io/blog/2011/05/27/di-mock</id>
422    <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>
423
424<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>
425
426<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>
427
428<p><strong>ILogService</strong> – describes a simple logging service. The ConsoleLogService implementation prints logs to the console.</p>
429
430<!-- more -->
431<p>### Dependency Injection &amp;Testing</p>
432
433<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>
434
435<div><table class="CodeRay"><tr>
436  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
437<a href="#n2" name="n2">2</a>
438<a href="#n3" name="n3">3</a>
439<a href="#n4" name="n4">4</a>
440<a href="#n5" name="n5">5</a>
441<a href="#n6" name="n6">6</a>
442<a href="#n7" name="n7">7</a>
443<a href="#n8" name="n8">8</a>
444<a href="#n9" name="n9">9</a>
445<strong><a href="#n10" name="n10">10</a></strong>
446<a href="#n11" name="n11">11</a>
447<a href="#n12" name="n12">12</a>
448<a href="#n13" name="n13">13</a>
449<a href="#n14" name="n14">14</a>
450</pre></td>
451  <td class="code"><pre><span class="directive">static</span> IContainer afContainer;
452
453[ClassInitialize]
454<span class="directive">public</span> <span class="directive">static</span> <span class="type">void</span> TestInit(TestContext ctx) {
455    var idSvc = A.Fake&lt;IIdentService&gt;();
456    A.CallTo(() =&gt; idSvc.GetCurrentUserName())
457        .Returns(<span class="string"><span class="delimiter">&quot;</span><span class="content">FAKE-ID</span><span class="delimiter">&quot;</span></span>);
458
459    var bldr = <span class="keyword">new</span> ContainerBuilder();
460    bldr.RegisterInstance(idSvc);
461    bldr.RegisterInstance(A.Fake&lt;ILogService&gt;());
462    bldr.RegisterType&lt;DevDataProvider&gt;().As&lt;IDataProvider&gt;();
463    afContainer = bldr.Build();
464}
465</pre></td>
466</tr></table>
467</div>
468
469<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>
470
471<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>
472
473<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>
474
475<div><table class="CodeRay"><tr>
476  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
477<a href="#n2" name="n2">2</a>
478<a href="#n3" name="n3">3</a>
479<a href="#n4" name="n4">4</a>
480<a href="#n5" name="n5">5</a>
481<a href="#n6" name="n6">6</a>
482<a href="#n7" name="n7">7</a>
483<a href="#n8" name="n8">8</a>
484</pre></td>
485  <td class="code"><pre>[TestMethod()]
486<span class="directive">public</span> <span class="type">void</span> GetCurrentEmployeeTest() {
487    var e = <span class="keyword">new</span> Employee { WindowsUsername = <span class="string"><span class="delimiter">&quot;</span><span class="content">FAKE-ID</span><span class="delimiter">&quot;</span></span> };
488    var dal = afContainer.Resolve&lt;IDataProvider&gt;();
489    dal.AddEmployee(e);
490    var result = dal.GetCurrentEmployee();
491    Assert.AreEqual(e.WindowsUsername, result.WindowsUsername);
492}
493</pre></td>
494</tr></table>
495</div>
496
497<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>
498
499<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>
500]]></content>
501  </entry>
502  
503  <entry>
504    <title type="html"><![CDATA[Practical Dependency Injection 101]]></title>
505    <link href="http://efvincent.github.io/blog/2011/05/27/practical-di-101/"/>
506    <updated>2011-05-27T13:08:27-04:00</updated>
507    <id>http://efvincent.github.io/blog/2011/05/27/practical-di-101</id>
508    <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>
509
510<!-- more -->
511<p>### What is Dependency Injection</p>
512
513<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>
514
515<p>How does DI reduce help reduce coupling? The easiest way to describe it is by diving directly into an example.</p>
516
517<h3 id="example-scenario">Example Scenario</h3>
518
519<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>
520
521<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>
522
523<p>Here’s the base level example program with no consideration for dependency injection:</p>
524
525<div><table class="CodeRay"><tr>
526  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
527<a href="#n2" name="n2">2</a>
528<a href="#n3" name="n3">3</a>
529<a href="#n4" name="n4">4</a>
530<a href="#n5" name="n5">5</a>
531<a href="#n6" name="n6">6</a>
532<a href="#n7" name="n7">7</a>
533<a href="#n8" name="n8">8</a>
534<a href="#n9" name="n9">9</a>
535<strong><a href="#n10" name="n10">10</a></strong>
536<a href="#n11" name="n11">11</a>
537<a href="#n12" name="n12">12</a>
538<a href="#n13" name="n13">13</a>
539<a href="#n14" name="n14">14</a>
540<a href="#n15" name="n15">15</a>
541<a href="#n16" name="n16">16</a>
542<a href="#n17" name="n17">17</a>
543<a href="#n18" name="n18">18</a>
544<a href="#n19" name="n19">19</a>
545<strong><a href="#n20" name="n20">20</a></strong>
546<a href="#n21" name="n21">21</a>
547<a href="#n22" name="n22">22</a>
548<a href="#n23" name="n23">23</a>
549<a href="#n24" name="n24">24</a>
550<a href="#n25" name="n25">25</a>
551<a href="#n26" name="n26">26</a>
552<a href="#n27" name="n27">27</a>
553<a href="#n28" name="n28">28</a>
554<a href="#n29" name="n29">29</a>
555<strong><a href="#n30" name="n30">30</a></strong>
556<a href="#n31" name="n31">31</a>
557<a href="#n32" name="n32">32</a>
558<a href="#n33" name="n33">33</a>
559<a href="#n34" name="n34">34</a>
560<a href="#n35" name="n35">35</a>
561<a href="#n36" name="n36">36</a>
562<a href="#n37" name="n37">37</a>
563<a href="#n38" name="n38">38</a>
564<a href="#n39" name="n39">39</a>
565<strong><a href="#n40" name="n40">40</a></strong>
566<a href="#n41" name="n41">41</a>
567<a href="#n42" name="n42">42</a>
568<a href="#n43" name="n43">43</a>
569<a href="#n44" name="n44">44</a>
570<a href="#n45" name="n45">45</a>
571<a href="#n46" name="n46">46</a>
572<a href="#n47" name="n47">47</a>
573<a href="#n48" name="n48">48</a>
574<a href="#n49" name="n49">49</a>
575<strong><a href="#n50" name="n50">50</a></strong>
576<a href="#n51" name="n51">51</a>
577<a href="#n52" name="n52">52</a>
578<a href="#n53" name="n53">53</a>
579<a href="#n54" name="n54">54</a>
580<a href="#n55" name="n55">55</a>
581<a href="#n56" name="n56">56</a>
582<a href="#n57" name="n57">57</a>
583<a href="#n58" name="n58">58</a>
584<a href="#n59" name="n59">59</a>
585<strong><a href="#n60" name="n60">60</a></strong>
586<a href="#n61" name="n61">61</a>
587</pre></td>
588  <td class="code"><pre><span class="type">class</span> <span class="class">Program</span> {
589    <span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
590
591        <span class="comment">// ** Without using an DI Container approach **</span>
592
593        <span class="comment">// Create a new provider aka data access layer</span>
594        var dal = <span class="keyword">new</span> DevDataProvider();
595
596        <span class="comment">// New up an employee that's supposed to represent the currently logged in user</span>
597        var e = <span class="keyword">new</span> Employee() {
598            WindowsUsername = <span class="string"><span class="delimiter">&quot;</span><span class="content">thanos</span><span class="char">\\</span><span class="content">efvincent</span><span class="delimiter">&quot;</span></span>,
599            EmployeeId = <span class="string"><span class="delimiter">&quot;</span><span class="content">0001</span><span class="delimiter">&quot;</span></span>,
600            FName = <span class="string"><span class="delimiter">&quot;</span><span class="content">Eric</span><span class="delimiter">&quot;</span></span>,
601            LName = <span class="string"><span class="delimiter">&quot;</span><span class="content">Vincent</span><span class="delimiter">&quot;</span></span>
602        };
603
604        <span class="comment">// Add it to the data access layer</span>
605        dal.AddEmployee(e);
606
607        <span class="comment">// See if the dal can find the current user</span>
608        e = dal.GetCurrentEmployee();
609
610        Console.WriteLine(
611            <span class="string"><span class="delimiter">&quot;</span><span class="content">Current logged in person is: {0}</span><span class="delimiter">&quot;</span></span>, e == <span class="predefined-constant">null</span> ? <span class="string"><span class="delimiter">&quot;</span><span class="content">unknown</span><span class="delimiter">&quot;</span></span> : e.FName);
612
613        <span class="comment">// End</span>
614        Console.Write(<span class="string"><span class="delimiter">&quot;</span><span class="content">Press any key...</span><span class="delimiter">&quot;</span></span>);
615        Console.ReadKey(<span class="predefined-constant">true</span>);
616
617    }
618}
619
620<span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> {
621    <span class="directive">private</span> <span class="directive">static</span> readonly <span class="predefined-type">List</span>&lt;Employee&gt; EmployeeStore = <span class="keyword">new</span> <span class="predefined-type">List</span>&lt;Employee&gt;();
622
623    <span class="directive">public</span> Employee GetCurrentEmployee() {
624        var emp = EmployeeStore.FirstOrDefault(
625            e =&gt; e.WindowsUsername.Equals(GetCurrentUserName(), StringComparison.OrdinalIgnoreCase));
626        <span class="keyword">return</span> emp;
627    }
628
629    <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
630        EmployeeStore.Add(e);
631    }
632
633    <span class="directive">public</span> IQueryable&lt;Employee&gt; Employees() {
634        <span class="keyword">return</span> EmployeeStore.AsQueryable();
635    }
636
637    <span class="directive">private</span> <span class="directive">static</span> string GetCurrentUserName() {
638        var wu = WindowsIdentity.GetCurrent();
639        <span class="keyword">return</span> wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
640    }
641}
642
643<span class="directive">public</span> <span class="type">class</span> <span class="class">Employee</span> {
644    <span class="directive">public</span> string WindowsUsername { get; set; }
645    <span class="directive">public</span> string EmployeeId { get; set; }
646    <span class="directive">public</span> string FName { get; set; }
647    <span class="directive">public</span> string LName { get; set; }
648}
649</pre></td>
650</tr></table>
651</div>
652
653<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>
654
655<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>
656
657<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>
658
659<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>
660
661<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>
662
663<h3 id="step-one--leveraging-interfaces">Step One – Leveraging Interfaces</h3>
664
665<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>
666
667<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>
668
669<div><table class="CodeRay"><tr>
670  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
671<a href="#n2" name="n2">2</a>
672<a href="#n3" name="n3">3</a>
673<a href="#n4" name="n4">4</a>
674<a href="#n5" name="n5">5</a>
675<a href="#n6" name="n6">6</a>
676<a href="#n7" name="n7">7</a>
677<a href="#n8" name="n8">8</a>
678<a href="#n9" name="n9">9</a>
679<strong><a href="#n10" name="n10">10</a></strong>
680<a href="#n11" name="n11">11</a>
681<a href="#n12" name="n12">12</a>
682<a href="#n13" name="n13">13</a>
683<a href="#n14" name="n14">14</a>
684<a href="#n15" name="n15">15</a>
685<a href="#n16" name="n16">16</a>
686<a href="#n17" name="n17">17</a>
687<a href="#n18" name="n18">18</a>
688<a href="#n19" name="n19">19</a>
689<strong><a href="#n20" name="n20">20</a></strong>
690<a href="#n21" name="n21">21</a>
691<a href="#n22" name="n22">22</a>
692<a href="#n23" name="n23">23</a>
693<a href="#n24" name="n24">24</a>
694<a href="#n25" name="n25">25</a>
695<a href="#n26" name="n26">26</a>
696<a href="#n27" name="n27">27</a>
697<a href="#n28" name="n28">28</a>
698<a href="#n29" name="n29">29</a>
699<strong><a href="#n30" name="n30">30</a></strong>
700<a href="#n31" name="n31">31</a>
701<a href="#n32" name="n32">32</a>
702<a href="#n33" name="n33">33</a>
703<a href="#n34" name="n34">34</a>
704<a href="#n35" name="n35">35</a>
705<a href="#n36" name="n36">36</a>
706<a href="#n37" name="n37">37</a>
707<a href="#n38" name="n38">38</a>
708<a href="#n39" name="n39">39</a>
709<strong><a href="#n40" name="n40">40</a></strong>
710<a href="#n41" name="n41">41</a>
711<a href="#n42" name="n42">42</a>
712<a href="#n43" name="n43">43</a>
713<a href="#n44" name="n44">44</a>
714<a href="#n45" name="n45">45</a>
715<a href="#n46" name="n46">46</a>
716<a href="#n47" name="n47">47</a>
717</pre></td>
718  <td class="code"><pre><span class="comment">// Interface defining an identity service</span>
719<span class="directive">public</span> <span class="type">interface</span> <span class="class">IIdentService</span> {
720    string GetCurrentUserName();
721}
722
723<span class="comment">// Implementation of an identity service that returns the current</span>
724<span class="comment">// logged in windows username</span>
725<span class="directive">public</span> <span class="type">class</span> <span class="class">WindowsIdentService</span> : IIdentService {
726    <span class="directive">public</span> string GetCurrentUserName() {
727        var wu = WindowsIdentity.GetCurrent();
728        <span class="keyword">return</span> wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
729    }
730}
731
732<span class="comment">// Interface defining a data provider service</span>
733<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