PageRenderTime 6ms CodeModel.GetById 6ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 1ms

/blog/categories/basics/atom.xml

https://github.com/efvincent/efvincent.github.io
XML | 1011 lines | 808 code | 198 blank | 5 comment | 0 complexity | 1c8dd29f771fbcb7b75c8c055ccb9e7c 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[Category: Basics | Curried Functions]]></title>
  5  <link href="http://efvincent.github.io/blog/categories/basics/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[DI – Constructor Injection, Bootstrapping]]></title>
 18    <link href="http://efvincent.github.io/blog/2011/06/24/di-bootstrap/"/>
 19    <updated>2011-06-24T02:07:31-04:00</updated>
 20    <id>http://efvincent.github.io/blog/2011/06/24/di-bootstrap</id>
 21    <content type="html"><![CDATA[<h2 id="constructor-injection">Constructor Injection</h2>
 22<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.
 23<!-- more -->
 24There 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>
 25
 26<div><table class="CodeRay"><tr>
 27  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 28<a href="#n2" name="n2">2</a>
 29<a href="#n3" name="n3">3</a>
 30<a href="#n4" name="n4">4</a>
 31<a href="#n5" name="n5">5</a>
 32<a href="#n6" name="n6">6</a>
 33<a href="#n7" name="n7">7</a>
 34<a href="#n8" name="n8">8</a>
 35<a href="#n9" name="n9">9</a>
 36<strong><a href="#n10" name="n10">10</a></strong>
 37<a href="#n11" name="n11">11</a>
 38<a href="#n12" name="n12">12</a>
 39<a href="#n13" name="n13">13</a>
 40<a href="#n14" name="n14">14</a>
 41</pre></td>
 42  <td class="code"><pre><span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
 43    <span class="directive">private</span> readonly IIdentService _identService;
 44    <span class="directive">private</span> readonly ILogService _logSvc;
 45    <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;();
 46
 47    <span class="directive">public</span> DevDataProvider(IIdentService identService, ILogService logSvc) {
 48        <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>);
 49        <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>);
 50        _identService = identService;
 51        _logSvc = logSvc;
 52    }
 53
 54    <span class="comment">// Remaining implementation omitted for brevity</span>
 55}
 56</pre></td>
 57</tr></table>
 58</div>
 59
 60<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>
 61
 62<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>
 63
 64<h2 id="bootstrapping">Bootstrapping</h2>
 65
 66<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>
 67
 68<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>
 69
 70<h2 id="bootstrapping-a-console-application">Bootstrapping a Console Application</h2>
 71
 72<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>
 73
 74<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>
 75
 76<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>
 77
 78<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>
 79
 80<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>
 81
 82<h2 id="only-directly-reference-the-di-container-in-the-bootstrapper">Only Directly Reference the DI Container in the Bootstrapper</h2>
 83<p>This is an important point, and if you get nothing else from this post, understand this.</p>
 84
 85<ul>
 86  <li>The DI container is configured in the composition root (Main() in this case)</li>
 87  <li>The DI container is used to resolve or build the App</li>
 88  <li>The app is then run to do the work</li>
 89</ul>
 90
 91<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>
 92
 93<h4 id="weve-taken-on-a-dependency-to-the-di-container-itself">We’ve taken on a dependency to the DI Container itself</h4>
 94
 95<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>
 96
 97<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>
 98
 99<h4 id="were-hiding-a-dependency-inside-the-app">We’re hiding a dependency inside the App</h4>
100
101<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>
102
103<div><table class="CodeRay"><tr>
104  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
105<a href="#n2" name="n2">2</a>
106<a href="#n3" name="n3">3</a>
107<a href="#n4" name="n4">4</a>
108<a href="#n5" name="n5">5</a>
109<a href="#n6" name="n6">6</a>
110<a href="#n7" name="n7">7</a>
111<a href="#n8" name="n8">8</a>
112</pre></td>
113  <td class="code"><pre><span class="comment">// Anti-pattern - don't use DI container except</span>
114<span class="comment">// in composition root</span>
115
116var dal = <span class="predefined-type">Container</span>.Resolve&lt;IDataAccessService&gt;();
117
118<span class="comment">// And defintely don't do this</span>
119
120var dal = <span class="keyword">new</span> SqlDataAccessService(connectString);
121</pre></td>
122</tr></table>
123</div>
124
125<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>
126
127<h3 id="bootstrapping-in-other-application-types">Bootstrapping in other Application Types</h3>
128
129<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>
130
131<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>
132
133<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>
134
135<h3 id="di-unfriendly-application-types">DI Unfriendly Application Types</h3>
136
137<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>
138
139<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>
140
141<h3 id="in-summary">In Summary</h3>
142
143<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>
144]]></content>
145  </entry>
146  
147  <entry>
148    <title type="html"><![CDATA[A Taste of Dependency Injection, Testing, and Mocking]]></title>
149    <link href="http://efvincent.github.io/blog/2011/05/27/di-mock/"/>
150    <updated>2011-05-27T20:28:53-04:00</updated>
151    <id>http://efvincent.github.io/blog/2011/05/27/di-mock</id>
152    <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>
153
154<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>
155
156<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>
157
158<p><strong>ILogService</strong> – describes a simple logging service. The ConsoleLogService implementation prints logs to the console.</p>
159
160<!-- more -->
161<p>### Dependency Injection &amp;Testing</p>
162
163<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>
164
165<div><table class="CodeRay"><tr>
166  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
167<a href="#n2" name="n2">2</a>
168<a href="#n3" name="n3">3</a>
169<a href="#n4" name="n4">4</a>
170<a href="#n5" name="n5">5</a>
171<a href="#n6" name="n6">6</a>
172<a href="#n7" name="n7">7</a>
173<a href="#n8" name="n8">8</a>
174<a href="#n9" name="n9">9</a>
175<strong><a href="#n10" name="n10">10</a></strong>
176<a href="#n11" name="n11">11</a>
177<a href="#n12" name="n12">12</a>
178<a href="#n13" name="n13">13</a>
179<a href="#n14" name="n14">14</a>
180</pre></td>
181  <td class="code"><pre><span class="directive">static</span> IContainer afContainer;
182
183[ClassInitialize]
184<span class="directive">public</span> <span class="directive">static</span> <span class="type">void</span> TestInit(TestContext ctx) {
185    var idSvc = A.Fake&lt;IIdentService&gt;();
186    A.CallTo(() =&gt; idSvc.GetCurrentUserName())
187        .Returns(<span class="string"><span class="delimiter">&quot;</span><span class="content">FAKE-ID</span><span class="delimiter">&quot;</span></span>);
188
189    var bldr = <span class="keyword">new</span> ContainerBuilder();
190    bldr.RegisterInstance(idSvc);
191    bldr.RegisterInstance(A.Fake&lt;ILogService&gt;());
192    bldr.RegisterType&lt;DevDataProvider&gt;().As&lt;IDataProvider&gt;();
193    afContainer = bldr.Build();
194}
195</pre></td>
196</tr></table>
197</div>
198
199<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>
200
201<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>
202
203<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>
204
205<div><table class="CodeRay"><tr>
206  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
207<a href="#n2" name="n2">2</a>
208<a href="#n3" name="n3">3</a>
209<a href="#n4" name="n4">4</a>
210<a href="#n5" name="n5">5</a>
211<a href="#n6" name="n6">6</a>
212<a href="#n7" name="n7">7</a>
213<a href="#n8" name="n8">8</a>
214</pre></td>
215  <td class="code"><pre>[TestMethod()]
216<span class="directive">public</span> <span class="type">void</span> GetCurrentEmployeeTest() {
217    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> };
218    var dal = afContainer.Resolve&lt;IDataProvider&gt;();
219    dal.AddEmployee(e);
220    var result = dal.GetCurrentEmployee();
221    Assert.AreEqual(e.WindowsUsername, result.WindowsUsername);
222}
223</pre></td>
224</tr></table>
225</div>
226
227<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>
228
229<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>
230]]></content>
231  </entry>
232  
233  <entry>
234    <title type="html"><![CDATA[Practical Dependency Injection 101]]></title>
235    <link href="http://efvincent.github.io/blog/2011/05/27/practical-di-101/"/>
236    <updated>2011-05-27T13:08:27-04:00</updated>
237    <id>http://efvincent.github.io/blog/2011/05/27/practical-di-101</id>
238    <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>
239
240<!-- more -->
241<p>### What is Dependency Injection</p>
242
243<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>
244
245<p>How does DI reduce help reduce coupling? The easiest way to describe it is by diving directly into an example.</p>
246
247<h3 id="example-scenario">Example Scenario</h3>
248
249<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>
250
251<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>
252
253<p>Here’s the base level example program with no consideration for dependency injection:</p>
254
255<div><table class="CodeRay"><tr>
256  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
257<a href="#n2" name="n2">2</a>
258<a href="#n3" name="n3">3</a>
259<a href="#n4" name="n4">4</a>
260<a href="#n5" name="n5">5</a>
261<a href="#n6" name="n6">6</a>
262<a href="#n7" name="n7">7</a>
263<a href="#n8" name="n8">8</a>
264<a href="#n9" name="n9">9</a>
265<strong><a href="#n10" name="n10">10</a></strong>
266<a href="#n11" name="n11">11</a>
267<a href="#n12" name="n12">12</a>
268<a href="#n13" name="n13">13</a>
269<a href="#n14" name="n14">14</a>
270<a href="#n15" name="n15">15</a>
271<a href="#n16" name="n16">16</a>
272<a href="#n17" name="n17">17</a>
273<a href="#n18" name="n18">18</a>
274<a href="#n19" name="n19">19</a>
275<strong><a href="#n20" name="n20">20</a></strong>
276<a href="#n21" name="n21">21</a>
277<a href="#n22" name="n22">22</a>
278<a href="#n23" name="n23">23</a>
279<a href="#n24" name="n24">24</a>
280<a href="#n25" name="n25">25</a>
281<a href="#n26" name="n26">26</a>
282<a href="#n27" name="n27">27</a>
283<a href="#n28" name="n28">28</a>
284<a href="#n29" name="n29">29</a>
285<strong><a href="#n30" name="n30">30</a></strong>
286<a href="#n31" name="n31">31</a>
287<a href="#n32" name="n32">32</a>
288<a href="#n33" name="n33">33</a>
289<a href="#n34" name="n34">34</a>
290<a href="#n35" name="n35">35</a>
291<a href="#n36" name="n36">36</a>
292<a href="#n37" name="n37">37</a>
293<a href="#n38" name="n38">38</a>
294<a href="#n39" name="n39">39</a>
295<strong><a href="#n40" name="n40">40</a></strong>
296<a href="#n41" name="n41">41</a>
297<a href="#n42" name="n42">42</a>
298<a href="#n43" name="n43">43</a>
299<a href="#n44" name="n44">44</a>
300<a href="#n45" name="n45">45</a>
301<a href="#n46" name="n46">46</a>
302<a href="#n47" name="n47">47</a>
303<a href="#n48" name="n48">48</a>
304<a href="#n49" name="n49">49</a>
305<strong><a href="#n50" name="n50">50</a></strong>
306<a href="#n51" name="n51">51</a>
307<a href="#n52" name="n52">52</a>
308<a href="#n53" name="n53">53</a>
309<a href="#n54" name="n54">54</a>
310<a href="#n55" name="n55">55</a>
311<a href="#n56" name="n56">56</a>
312<a href="#n57" name="n57">57</a>
313<a href="#n58" name="n58">58</a>
314<a href="#n59" name="n59">59</a>
315<strong><a href="#n60" name="n60">60</a></strong>
316<a href="#n61" name="n61">61</a>
317</pre></td>
318  <td class="code"><pre><span class="type">class</span> <span class="class">Program</span> {
319    <span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
320
321        <span class="comment">// ** Without using an DI Container approach **</span>
322
323        <span class="comment">// Create a new provider aka data access layer</span>
324        var dal = <span class="keyword">new</span> DevDataProvider();
325
326        <span class="comment">// New up an employee that's supposed to represent the currently logged in user</span>
327        var e = <span class="keyword">new</span> Employee() {
328            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>,
329            EmployeeId = <span class="string"><span class="delimiter">&quot;</span><span class="content">0001</span><span class="delimiter">&quot;</span></span>,
330            FName = <span class="string"><span class="delimiter">&quot;</span><span class="content">Eric</span><span class="delimiter">&quot;</span></span>,
331            LName = <span class="string"><span class="delimiter">&quot;</span><span class="content">Vincent</span><span class="delimiter">&quot;</span></span>
332        };
333
334        <span class="comment">// Add it to the data access layer</span>
335        dal.AddEmployee(e);
336
337        <span class="comment">// See if the dal can find the current user</span>
338        e = dal.GetCurrentEmployee();
339
340        Console.WriteLine(
341            <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);
342
343        <span class="comment">// End</span>
344        Console.Write(<span class="string"><span class="delimiter">&quot;</span><span class="content">Press any key...</span><span class="delimiter">&quot;</span></span>);
345        Console.ReadKey(<span class="predefined-constant">true</span>);
346
347    }
348}
349
350<span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> {
351    <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;();
352
353    <span class="directive">public</span> Employee GetCurrentEmployee() {
354        var emp = EmployeeStore.FirstOrDefault(
355            e =&gt; e.WindowsUsername.Equals(GetCurrentUserName(), StringComparison.OrdinalIgnoreCase));
356        <span class="keyword">return</span> emp;
357    }
358
359    <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
360        EmployeeStore.Add(e);
361    }
362
363    <span class="directive">public</span> IQueryable&lt;Employee&gt; Employees() {
364        <span class="keyword">return</span> EmployeeStore.AsQueryable();
365    }
366
367    <span class="directive">private</span> <span class="directive">static</span> string GetCurrentUserName() {
368        var wu = WindowsIdentity.GetCurrent();
369        <span class="keyword">return</span> wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
370    }
371}
372
373<span class="directive">public</span> <span class="type">class</span> <span class="class">Employee</span> {
374    <span class="directive">public</span> string WindowsUsername { get; set; }
375    <span class="directive">public</span> string EmployeeId { get; set; }
376    <span class="directive">public</span> string FName { get; set; }
377    <span class="directive">public</span> string LName { get; set; }
378}
379</pre></td>
380</tr></table>
381</div>
382
383<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>
384
385<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>
386
387<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>
388
389<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>
390
391<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>
392
393<h3 id="step-one--leveraging-interfaces">Step One – Leveraging Interfaces</h3>
394
395<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>
396
397<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>
398
399<div><table class="CodeRay"><tr>
400  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
401<a href="#n2" name="n2">2</a>
402<a href="#n3" name="n3">3</a>
403<a href="#n4" name="n4">4</a>
404<a href="#n5" name="n5">5</a>
405<a href="#n6" name="n6">6</a>
406<a href="#n7" name="n7">7</a>
407<a href="#n8" name="n8">8</a>
408<a href="#n9" name="n9">9</a>
409<strong><a href="#n10" name="n10">10</a></strong>
410<a href="#n11" name="n11">11</a>
411<a href="#n12" name="n12">12</a>
412<a href="#n13" name="n13">13</a>
413<a href="#n14" name="n14">14</a>
414<a href="#n15" name="n15">15</a>
415<a href="#n16" name="n16">16</a>
416<a href="#n17" name="n17">17</a>
417<a href="#n18" name="n18">18</a>
418<a href="#n19" name="n19">19</a>
419<strong><a href="#n20" name="n20">20</a></strong>
420<a href="#n21" name="n21">21</a>
421<a href="#n22" name="n22">22</a>
422<a href="#n23" name="n23">23</a>
423<a href="#n24" name="n24">24</a>
424<a href="#n25" name="n25">25</a>
425<a href="#n26" name="n26">26</a>
426<a href="#n27" name="n27">27</a>
427<a href="#n28" name="n28">28</a>
428<a href="#n29" name="n29">29</a>
429<strong><a href="#n30" name="n30">30</a></strong>
430<a href="#n31" name="n31">31</a>
431<a href="#n32" name="n32">32</a>
432<a href="#n33" name="n33">33</a>
433<a href="#n34" name="n34">34</a>
434<a href="#n35" name="n35">35</a>
435<a href="#n36" name="n36">36</a>
436<a href="#n37" name="n37">37</a>
437<a href="#n38" name="n38">38</a>
438<a href="#n39" name="n39">39</a>
439<strong><a href="#n40" name="n40">40</a></strong>
440<a href="#n41" name="n41">41</a>
441<a href="#n42" name="n42">42</a>
442<a href="#n43" name="n43">43</a>
443<a href="#n44" name="n44">44</a>
444<a href="#n45" name="n45">45</a>
445<a href="#n46" name="n46">46</a>
446<a href="#n47" name="n47">47</a>
447</pre></td>
448  <td class="code"><pre><span class="comment">// Interface defining an identity service</span>
449<span class="directive">public</span> <span class="type">interface</span> <span class="class">IIdentService</span> {
450    string GetCurrentUserName();
451}
452
453<span class="comment">// Implementation of an identity service that returns the current</span>
454<span class="comment">// logged in windows username</span>
455<span class="directive">public</span> <span class="type">class</span> <span class="class">WindowsIdentService</span> : IIdentService {
456    <span class="directive">public</span> string GetCurrentUserName() {
457        var wu = WindowsIdentity.GetCurrent();
458        <span class="keyword">return</span> wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
459    }
460}
461
462<span class="comment">// Interface defining a data provider service</span>
463<span class="directive">public</span> <span class="type">interface</span> <span class="class">IDataProvider</span> {
464    Employee GetCurrentEmployee();
465    <span class="type">void</span> AddEmployee(Employee e);
466    IQueryable&lt;Employee&gt; Employees();
467}
468
469<span class="comment">// Our development data provider now implements the interface</span>
470<span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
471    <span class="directive">private</span> readonly IIdentService _identService;
472    <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;();
473
474    <span class="directive">public</span> DevDataProvider(IIdentService identService) {
475        <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>);
476        _identService = identService;
477    }
478
479    <span class="directive">public</span> Employee GetCurrentEmployee() {
480        var emp = EmployeeStore.FirstOrDefault(
481                        e =&gt; e.WindowsUsername.Equals(
482                            _identService.GetCurrentUserName(),
483                            StringComparison.OrdinalIgnoreCase));
484        <span class="keyword">return</span> emp;
485    }
486
487    <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
488        EmployeeStore.Add(e);
489    }
490
491    <span class="directive">public</span> IQueryable&lt;Employee&gt; Employees() {
492        <span class="keyword">return</span> EmployeeStore.AsQueryable();
493    }
494}
495</pre></td>
496</tr></table>
497</div>
498
499<p>We’re part of the way to where we need to be. Altering DevDataProvider to depend on the IIdentService interface frees it from a hard dependency on a particular identity implementation. The downside is we’ve made creation of the DevDataProvider a bit more complex, as we need to supply the new instance with an IIdentityService instance.</p>
500
501<p>~~~C#
502// Create a new ident service, required for the DAL
503IIdentService identSvc = new WindowsIdentService();</p>
504
505<p>// Create a new DAL
506IDataProvider dal = new DevDataProvider(identSvc);
507~~~</p>
508
509<p>The DevDataProvider now takes a constructor parameter of type IIdentService. This is where the <em>injection</em> in dependency injection comes from. DevDataProvider has a dependency, but instead of hard coding it into the definition of DevDataProvider, we inject it. There are different ways of injecting dependencies, but constructor injection is very popular and works well in many, or even most cases.</p>
510
511<p>The complexity of constructing instances increases when we add a simple logging service which logs information or errors messages.</p>
512
513<p>~~~C#
514// Interface defining a logging service
515public interface ILogService {
516    void LogInfo(string msg, params object[] args);
517    void LogError(string msg, params object[] args);
518}</p>
519
520<p>// Implementation of a console logging service
521public class ConsoleLogger : ILogService {
522    public void LogInfo(string msg, params object[] args) {
523        Console.WriteLine(
524            “{0} INFO: {1}”, DateTime.Now,
525            string.Format(msg, args));
526    }</p>
527
528<pre><code>public void LogError(string msg, params object[] args) {
529    Console.WriteLine(
530        "{0} ERROR: {1}", DateTime.Now,
531        string.Format(msg, args));
532} } ~~~
533</code></pre>
534
535<p>The ILogService is implemented by a simple console logger. Now both the WindowsIdentService and the DevDataProvider can leverage the logger. They’re both modified to have ILogService instance injected via their respective constructors.</p>
536
537<div><table class="CodeRay"><tr>
538  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
539<a href="#n2" name="n2">2</a>
540<a href="#n3" name="n3">3</a>
541<a href="#n4" name="n4">4</a>
542<a href="#n5" name="n5">5</a>
543<a href="#n6" name="n6">6</a>
544<a href="#n7" name="n7">7</a>
545<a href="#n8" name="n8">8</a>
546<a href="#n9" name="n9">9</a>
547<strong><a href="#n10" name="n10">10</a></strong>
548<a href="#n11" name="n11">11</a>
549<a href="#n12" name="n12">12</a>
550<a href="#n13" name="n13">13</a>
551<a href="#n14" name="n14">14</a>
552<a href="#n15" name="n15">15</a>
553<a href="#n16" name="n16">16</a>
554<a href="#n17" name="n17">17</a>
555<a href="#n18" name="n18">18</a>
556<a href="#n19" name="n19">19</a>
557<strong><a href="#n20" name="n20">20</a></strong>
558<a href="#n21" name="n21">21</a>
559<a href="#n22" name="n22">22</a>
560<a href="#n23" name="n23">23</a>
561<a href="#n24" name="n24">24</a>
562<a href="#n25" name="n25">25</a>
563<a href="#n26" name="n26">26</a>
564<a href="#n27" name="n27">27</a>
565<a href="#n28" name="n28">28</a>
566<a href="#n29" name="n29">29</a>
567<strong><a href="#n30" name="n30">30</a></strong>
568<a href="#n31" name="n31">31</a>
569<a href="#n32" name="n32">32</a>
570<a href="#n33" name="n33">33</a>
571<a href="#n34" name="n34">34</a>
572<a href="#n35" name="n35">35</a>
573<a href="#n36" name="n36">36</a>
574<a href="#n37" name="n37">37</a>
575<a href="#n38" name="n38">38</a>
576<a href="#n39" name="n39">39</a>
577<strong><a href="#n40" name="n40">40</a></strong>
578<a href="#n41" name="n41">41</a>
579<a href="#n42" name="n42">42</a>
580<a href="#n43" name="n43">43</a>
581<a href="#n44" name="n44">44</a>
582<a href="#n45" name="n45">45</a>
583<a href="#n46" name="n46">46</a>
584<a href="#n47" name="n47">47</a>
585<a href="#n48" name="n48">48</a>
586<a href="#n49" name="n49">49</a>
587</pre></td>
588  <td class="code"><pre><span class="comment">// Implementation of an identity service that returns the current</span>
589<span class="comment">// logged in windows username</span>
590<span class="directive">public</span> <span class="type">class</span> <span class="class">WindowsIdentService</span> : IIdentService {
591    <span class="directive">private</span> readonly ILogService _logSvc;
592
593    <span class="directive">public</span> WindowsIdentService(ILogService logSvc) {
594        <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>);
595        _logSvc = logSvc;
596    }
597
598    <span class="directive">public</span> string GetCurrentUserName() {
599        var wu = WindowsIdentity.GetCurrent();
600        var un = wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
601        _logSvc.LogInfo(<span class="string"><span class="delimiter">&quot;</span><span class="content">Identified current user as: {0}</span><span class="delimiter">&quot;</span></span>, un);
602        <span class="keyword">return</span> un;
603    }
604}
605
606<span class="comment">// Our development data provider now implements the interface</span>
607<span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
608    <span class="directive">private</span> readonly IIdentService _identService;
609    <span class="directive">private</span> readonly ILogService _logSvc;
610    <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;();
611
612    <span class="directive">public</span> DevDataProvider(IIdentService identService, ILogService logSvc) {
613        <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>);
614        <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>);
615        _identService = identService;
616        _logSvc = logSvc;
617    }
618
619    <span class="directive">public</span> Employee GetCurrentEmployee() {
620        var un = _identService.GetCurrentUserName();
621        var emp = EmployeeStore.FirstOrDefault(
622                        e =&gt; e.WindowsUsername.Equals(un,
623                            StringComparison.OrdinalIgnoreCase));
624        <span class="keyword">if</span> (emp == <span class="predefined-constant">null</span>) _logSvc.LogInfo(<span class="string"><span class="delimiter">&quot;</span><span class="content">Current employee {0} not found</span><span class="delimiter">&quot;</span></span>, un);
625        <span class="keyword">return</span> emp;
626    }
627
628    <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
629        EmployeeStore.Add(e);
630        _logSvc.LogInfo(<span class="string"><span class="delimiter">&quot;</span><span class="content">Added employee with id {0}</span><span class="delimiter">&quot;</span></span>, e.EmployeeId);
631    }
632
633    <span class="directive">public</span> IQueryable&lt;Employee&gt; Employees() {
634        <span class="keyword">return</span> EmployeeStore.AsQueryable();
635    }
636}
637</pre></td>
638</tr></table>
639</div>
640
641<p>Now the services are getting more robust and they’re not tightly coupled to each other, they refer only to interfaces of the services they depend on. Main() however, where construction is going on, is getting messy.</p>
642
643<div><table class="CodeRay"><tr>
644  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
645<a href="#n2" name="n2">2</a>
646<a href="#n3" name="n3">3</a>
647<a href="#n4" name="n4">4</a>
648<a href="#n5" name="n5">5</a>
649<a href="#n6" name="n6">6</a>
650<a href="#n7" name="n7">7</a>
651<a href="#n8" name="n8">8</a>
652<a href="#n9" name="n9">9</a>
653<strong><a href="#n10" name="n10">10</a></strong>
654<a href="#n11" name="n11">11</a>
655<a href="#n12" name="n12">12</a>
656</pre></td>
657  <td class="code"><pre><span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
658
659    <span class="comment">// ** Without using an DI Container approach **</span>
660
661    <span class="comment">// Create a new logging service, required for uh.. everything</span>
662    ILogService consoleLog = <span class="keyword">new</span> ConsoleLogger();
663
664    <span class="comment">// Create a new ident service, required for the DAL</span>
665    IIdentService identSvc = <span class="keyword">new</span> WindowsIdentService(consoleLog);
666
667    <span class="comment">// Create a new DAL</span>
668    IDataProvider dal = <span class="keyword">new</span> DevDataProvider(identSvc, consoleLog);
669</pre></td>
670</tr></table>
671</div>
672
673<p>Finally we’re at the point where we can see the benefit of an dependency injection container. One thing about DI containers is that they’re already written. Several mature, robust, open-source DI containers exist. We’ll use AutoFac, because that’s what I’ve been using lately. We include <a href="http://www.nuget.org/List/Packages/Autofac">AutoFac</a> using <a href="http://www.nuget.org">NuGet</a>.</p>
674
675<pre><code>// Create a singleton dependency injection container
676private static readonly IContainer Container = ConfigureContainer();
677
678// Configure the container
679static IContainer ConfigureContainer() {
680    // This is how AutoFac works. Other DI containers have similar
681    // mechanisms for configuring the container
682    var bld = new ContainerBuilder();
683
684    // Register the types that implement the interfaces that are required
685    // for injection. Note that we have robust control over lifetime, in
686    // this case ILogService and IIdentService will be singletons, and
687    // IDataProvider will provide a new instance each time it's requested
688    bld.RegisterType&lt;ConsoleLogger&gt;().As&lt;ILogService&gt;().SingleInstance();
689    bld.RegisterType&lt;WindowsIdentService&gt;().As&lt;IIdentService&gt;().SingleInstance();
690    bld.RegisterType&lt;DevDataProvider&gt;().As&lt;IDataProvider&gt;();
691    return bld.Build();
692}
693
694static void Main(string[] args) {
695
696    // ** Using an IoC Container approach **
697    var dal = Container.Resolve&lt;IDataProvider&gt;();
698</code></pre>
699
700<p>We’ve created a static instance of IContainer (an AutoFac DI container). When we start the app we configure the container, which fundamentally consists of mapping the interfaces to concrete types that will be injected. For example, line 14 specifies that when there’s a need for an instance of ILogService, we will create an instance of ConsoleLogger. It further says that the DI container should use a SingleInstance() of ConsoleLogger. This has the effect of making ConsoleLogger a singleton. In our example, both the WindowsIdentService and the DevDataProvider will be handed the same instance of ConsoleLogger.</p>
701
702<p>The magic happens when we call Container.Resolve<idataprovider>(). The container determines what concrete class to create, and it looks for any dependencies in the constructor. It will see that to build a DevDataProvider, it needs an ILogService and an IWindowsIdentService, it will recursively resolve those as well.</idataprovider></p>
703
704<p>These are the basics of dependency injection. Even in this simple example, it should be obvious that the components and classes that we can create can be designed with very low coupling and cohesion using this technique. There are anti-patterns for using DI as well. You should endeavor to practice this technique, do research and learn the most effective uses; there’s plenty of material out there.</p>
705
706<p>I hope this example was helpful. Next post I’ll extend this sample by looking at testing, and mock objects, and how DI injection can make testing far easier.</p>
707
708<p>Source code samples can be found at this <a href="https://bitbucket.org/efvincent/blog-post-dependency-injection-101">bitbucket repository</a>.</p>
709
710<p><em>Update:</em> Follow up post - <a href="http://efvincent.github.io/2011/05/28/di-mock">Dependency Injection, Testing, and Mocking</a></p>
711]]></content>
712  </entry>
713  
714  <entry>
715    <title type="html"><![CDATA[NuGet – Galleries of Geeky Goodness.]]></title>
716    <link href="http://efvincent.github.io/blog/2011/01/12/nuget-geeky-goodness/"/>
717    <updated>2011-01-12T18:27:26-05:00</updated>
718    <id>http://efvincent.github.io/blog/2011/01/12/nuget-geeky-goodness</id>
719    <content type="html"><![CDATA[<p>In a <a href="http://blog.efvincent.com/open-source-nuget-and-more/">previous post</a> I described how Scott Hanselman’s <a href="http://www.hanselman.com/blog/PDC10BuildingABlogWithMicrosoftUnnamedPackageOfWebLove.aspx">presentation</a> during PDC 2010 introduced me to several wonderful and interesting technologies that are either just now out or about to be. The first one I’ll discuss is <a href="http://nuget.codeplex.com">NuGet</a>. There are many excellent introductions to NuGet by <a href="http://www.hanselman.com/blog/IntroducingNuPackPackageManagementForNETAnotherPieceOfTheWebStack.aspx">Hanselman</a> and others. I’ll see if I can make a meaningful contribution.</p>
720
721<p>NuGet is an add-on to VS2010. It allows us to access <em>packages</em> that have been published either locally or publicly on the web. The main NuGet gallery just went live today at <a href="http://nuget.org">http://nuget.org</a>. These packages make it easy to install, update, and remove libraries and tools in Visual Studio 2010.</p>
722
723<!-- more -->
724
725<h2 id="installation">Installation</h2>
726
727<p>NuGet, like dozens of other useful add-ins, is available through the Visual Studio Extension Manager, reached under _Tools… Extension Manager…. _</p>
728
729<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/01/image.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/01/image_thumb.png" alt="image" /></a></p>
730
731<p>From the Extension Manager choose (1) the online gallery, and then (2) search for NuGet. A restart of Visual Studio is required.</p>
732
733<h2 id="the-nuget-package-manager-console">The NuGet Package Manager Console</h2>
734
735<p>NuGet has two user interfaces. There’s a PowerShell powered console window. This is the UI I was first introduced to and have gravitated towards. The console gives you a more complete sense of control over the process. Open the console by selecting <em>View… Other Windows… Package Manager Console</em>.</p>
736
737<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/01/image1.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/01/image_thumb1.png" alt="image" /></a></p>
738
739<p>The <em>Package Source</em> drop down defaults to the official NuGet package gallery. There are already hundreds of packages out in the gallery, and you can expect it to grow rapidly. You can list the packages in the official library with:<

Large files files are truncated, but you can click here to view the full file