PageRenderTime 20ms CodeModel.GetById 3ms app.highlight 5ms 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
   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:</p>
 740
 741<p>List-Packages –remote</p>
 742
 743<p>There are a lot of them, and since the console is PowerShell we can take advantage of a PowerShell grid display:</p>
 744
 745<table>
 746  <tbody>
 747    <tr>
 748      <td>List-Packages –remote</td>
 749      <td>out-GridView</td>
 750    </tr>
 751  </tbody>
 752</table>
 753
 754<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/01/image2.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/01/image_thumb2.png" alt="image" /></a></p>
 755
 756<h2 id="installing-and-removing-packages">Installing and Removing Packages</h2>
 757
 758<p>Now comes the really cool part. The whole idea of NuGet is to be able to install / add external libraries to your project without having to find them on the web, download a zip or msi file, install it somewhere on your local machine, figure out what the instructions are for incorporating them into your project, and patching it in manually.</p>
 759
 760<p>Let’s take for example, the latest CTP5 version of Entity Framework, that allows for <em>Code First</em> use of the Entity Framework. EF4 will justify at least one future dedicated post, but we’ll use it here for a quick example. Normally, if you want to try out something like a new version of Entity Framework, there’s downloading, installing, shaving the chicken, bla bla bla that you’ve got to do. Not with NuGet. NuGet can effectively _“_xcopy deploy” it into our project.</p>
 761
 762<p>Create a new console application in Visual Studio. From the Package Manager Console, type <em>Install-Package EF</em> and press the tab key. An intellisense window will pop up showing packages that begin with EF.</p>
 763
 764<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/01/image3.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/01/image_thumb3.png" alt="image" /></a></p>
 765
 766<p>At the time of this writing, there are five packages. The EFCTP4 ones are obsolete, from the last CTP. For this example, choose <em>EFCodeFirst</em> and press enter. The console displays license info, downloads the EFCodeFirst package, and incorporates it into your project. In the solution explorer, we can see a reference  (1) and a file (2) added to the project.</p>
 767
 768<p><a href="http://blog.efvincent.com/wp-content/uploads/2011/01/image4.png"><img src="http://blog.efvincent.com/wp-content/uploads/2011/01/image_thumb4.png" alt="image" /></a></p>
 769
 770<p>Checking the properties of the reference to EntityFramework, you can see that it’s not installed to the GAC, it’s local to the solution. NuGet creates a solution level folder called <em>packages</em>. In that folder, in addition to components used as references, is all the data that NuGet needs to install and uninstall packages. All local, without changing any configuration on the machine. More details of the inner workings of NuGet and its packages will come at a later date, plus there’s information out there you can dig up if you’re so inclined.</p>
 771
 772<h2 id="using-entity-framework">Using Entity Framework</h2>
 773
 774<p>Now that we’ve got it installed, let’s quickly use EFCodeFirst just to prove it’s working. For this example, you’ll need SQL Server installed (there are other options, but one thing at a time). I’ve got Express which works fine. In another post I’ll show the new SQL Server Compact Edition 4, which coincidentally you can add to a project using NuGet <img src="http://blog.efvincent.com/wp-content/uploads/2011/01/wlEmoticon-smile.png" alt="Smile" />.</p>
 775
 776<p>EFCodeFirst allows you to build POCO objects and use them to build a DB. Let’s build a quick model. There are a few examples floating around modeling blog posts and comments, so lets <em>not</em> do that. Let’s do (super simple) prescriptions and medications. It’s on my mind because I’m recovering from knee surgery. This code is entered directly into the Program.cs source file for this example.</p>
 777
 778<div><table class="CodeRay"><tr>
 779  <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
 780<a href="#n2" name="n2">2</a>
 781<a href="#n3" name="n3">3</a>
 782<a href="#n4" name="n4">4</a>
 783<a href="#n5" name="n5">5</a>
 784<a href="#n6" name="n6">6</a>
 785<a href="#n7" name="n7">7</a>
 786<a href="#n8" name="n8">8</a>
 787<a href="#n9" name="n9">9</a>
 788<strong><a href="#n10" name="n10">10</a></strong>
 789<a href="#n11" name="n11">11</a>
 790<a href="#n12" name="n12">12</a>
 791<a href="#n13" name="n13">13</a>
 792<a href="#n14" name="n14">14</a>
 793<a href="#n15" name="n15">15</a>
 794<a href="#n16" name="n16">16</a>
 795<a href="#n17" name="n17">17</a>
 796<a href="#n18" name="n18">18</a>
 797<a href="#n19" name="n19">19</a>
 798<strong><a href="#n20" name="n20">20</a></strong>
 799<a href="#n21" name="n21">21</a>
 800<a href="#n22" name="n22">22</a>
 801<a href="#n23" name="n23">23</a>
 802<a href="#n24" name="n24">24</a>
 803<a href="#n25" name="n25">25</a>
 804<a href="#n26" name="n26">26</a>
 805<a href="#n27" name="n27">27</a>
 806<a href="#n28" name="n28">28</a>
 807<a href="#n29" name="n29">29</a>
 808<strong><a href="#n30" name="n30">30</a></strong>
 809<a href="#n31" name="n31">31</a>
 810<a href="#n32" name="n32">32</a>
 811<a href="#n33" name="n33">33</a>
 812<a href="#n34" name="n34">34</a>
 813<a href="#n35" name="n35">35</a>
 814<a href="#n36" name="n36">36</a>
 815<a href="#n37" name="n37">37</a>
 816<a href="#n38" name="n38">38</a>
 817<a href="#n39" name="n39">39</a>
 818<strong><a href="#n40" name="n40">40</a></strong>
 819<a href="#n41" name="n41">41</a>
 820<a href="#n42" name="n42">42</a>
 821<a href="#n43" name="n43">43</a>
 822<a href="#n44" name="n44">44</a>
 823<a href="#n45" name="n45">45</a>
 824<a href="#n46" name="n46">46</a>
 825<a href="#n47" name="n47">47</a>
 826<a href="#n48" name="n48">48</a>
 827<a href="#n49" name="n49">49</a>
 828<strong><a href="#n50" name="n50">50</a></strong>
 829<a href="#n51" name="n51">51</a>
 830<a href="#n52" name="n52">52</a>
 831<a href="#n53" name="n53">53</a>
 832<a href="#n54" name="n54">54</a>
 833<a href="#n55" name="n55">55</a>
 834<a href="#n56" name="n56">56</a>
 835<a href="#n57" name="n57">57</a>
 836<a href="#n58" name="n58">58</a>
 837<a href="#n59" name="n59">59</a>
 838<strong><a href="#n60" name="n60">60</a></strong>
 839<a href="#n61" name="n61">61</a>
 840<a href="#n62" name="n62">62</a>
 841<a href="#n63" name="n63">63</a>
 842<a href="#n64" name="n64">64</a>
 843<a href="#n65" name="n65">65</a>
 844<a href="#n66" name="n66">66</a>
 845<a href="#n67" name="n67">67</a>
 846<a href="#n68" name="n68">68</a>
 847<a href="#n69" name="n69">69</a>
 848<strong><a href="#n70" name="n70">70</a></strong>
 849<a href="#n71" name="n71">71</a>
 850<a href="#n72" name="n72">72</a>
 851<a href="#n73" name="n73">73</a>
 852<a href="#n74" name="n74">74</a>
 853<a href="#n75" name="n75">75</a>
 854<a href="#n76" name="n76">76</a>
 855<a href="#n77" name="n77">77</a>
 856<a href="#n78" name="n78">78</a>
 857<a href="#n79" name="n79">79</a>
 858<strong><a href="#n80" name="n80">80</a></strong>
 859<a href="#n81" name="n81">81</a>
 860<a href="#n82" name="n82">82</a>
 861<a href="#n83" name="n83">83</a>
 862<a href="#n84" name="n84">84</a>
 863<a href="#n85" name="n85">85</a>
 864<a href="#n86" name="n86">86</a>
 865<a href="#n87" name="n87">87</a>
 866<a href="#n88" name="n88">88</a>
 867<a href="#n89" name="n89">89</a>
 868<strong><a href="#n90" name="n90">90</a></strong>
 869</pre></td>
 870  <td class="code"><pre><span class="directive">public</span> <span class="type">class</span> <span class="class">Prescription</span> {
 871    <span class="directive">public</span> <span class="type">int</span> Id { get; set; }
 872    <span class="directive">public</span> string MedName { get; set; }
 873    <span class="directive">public</span> string Directions { get; set; }
 874    <span class="directive">public</span> <span class="type">int</span> Quantity { get; set; }
 875    <span class="directive">public</span> <span class="type">int</span> Refills { get; set; }
 876    <span class="directive">public</span> <span class="type">int</span> RefillsRemaining { get; set; }
 877    <span class="directive">public</span> ICollection&lt;FilledScript&gt; FilledScripts { get; set; }
 878}
 879
 880<span class="directive">public</span> <span class="type">class</span> <span class="class">FilledScript</span> {
 881    <span class="directive">public</span> <span class="type">int</span> Id { get; set; }
 882    <span class="directive">public</span> Prescription Script { get; set; }
 883    <span class="directive">public</span> DateTime Filled { get; set; }
 884    <span class="directive">public</span> <span class="type">int</span> Doses { get; set; }
 885}
 886
 887<span class="directive">public</span> <span class="type">class</span> <span class="class">MedContext</span> : DbContext {
 888    <span class="directive">public</span> DbSet&lt;Prescription&gt; Prescriptions { get; set; }
 889    <span class="directive">public</span> DbSet&lt;FilledScript&gt; FilledScripts { get; set; }
 890}
 891<span class="error">`</span><span class="error">`</span><span class="error">`</span>
 892
 893We have a <span class="type">class</span> <span class="class">for</span> a Prescription, and one <span class="keyword">for</span> a FilledScript (filled prescription). We give each one an integer Id, which EF will interpret (by convention) as the primary key and identity <span class="keyword">for</span> each entity. A relation is created between them, again by convention. On the <span class="error">“</span>one<span class="error">”</span> side,<span class="error"> </span> the Prescription has a collection of filled scripts, and on the <span class="error">“</span>many<span class="error">”</span> side, the filled script has a reference to its prescription.
 894
 895The _MedContext_ <span class="type">class</span> <span class="class">inherits</span> from EF<span class="error">’</span>s DbContext, and pulls the model together. Each DbSet&lt;<span class="error">…</span>&gt; identifies an entity to EF. In <span class="local-variable">this</span> minimal <span class="keyword">case</span>, that<span class="error">’</span>s all that<span class="error">’</span>s required to define a model using EFCodeFirst. Lets take a look at using it:
 896
 897~~~java  
 898<span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
 899
 900    DbDatabase.SetInitializer(<span class="keyword">new</span> DropCreateDatabaseAlways&lt;MedContext&gt;());
 901
 902    var ctx = <span class="keyword">new</span> MedContext();
 903    var p = <span class="keyword">new</span> Prescription() {
 904        MedName = <span class="string"><span class="delimiter">&quot;</span><span class="content">Vicoden</span><span class="delimiter">&quot;</span></span>,
 905        Directions = <span class="string"><span class="delimiter">&quot;</span><span class="content">One every 4 hours as needed for pain</span><span class="delimiter">&quot;</span></span>,
 906        Quantity = <span class="integer">60</span>,
 907        Refills = <span class="integer">2</span>,
 908        RefillsRemaining = <span class="integer">1</span>,
 909        FilledScripts = <span class="keyword">new</span><span class="type">[]</span> {
 910            <span class="keyword">new</span> FilledScript() {
 911                Filled = DateTime.Parse(<span class="string"><span class="delimiter">&quot;</span><span class="content">12/28/2010</span><span class="delimiter">&quot;</span></span>),
 912                Doses = <span class="integer">0</span>
 913            },
 914            <span class="keyword">new</span> FilledScript() {
 915                Filled = DateTime.Parse(<span class="string"><span class="delimiter">&quot;</span><span class="content">1/12/2011</span><span class="delimiter">&quot;</span></span>),
 916                Doses = <span class="integer">48</span>
 917            }
 918        }
 919    };
 920
 921    ctx.Prescriptions.Add(p);
 922    ctx.SaveChanges();
 923
 924    foreach (var script in ctx.Prescriptions) {
 925        Console.WriteLine(<span class="string"><span class="delimiter">&quot;</span><span class="content">Script for {0}, filled {1} time(s), we have {2} doses on hand</span><span class="delimiter">&quot;</span></span>,
 926            script.MedName,
 927            script.FilledScripts.Count(),
 928            script.FilledScripts.Sum(fs =&gt; fs.Doses));
 929    }
 930
 931    Console.Write(<span class="string"><span class="delimiter">&quot;</span><span class="char">\n</span><span class="content">Press any key...</span><span class="delimiter">&quot;</span></span>);
 932    Console.ReadKey(<span class="predefined-constant">true</span>);
 933}
 934<span class="error">`</span><span class="error">`</span><span class="error">`</span>
 935
 936For <span class="local-variable">this</span> simple example I<span class="error">’</span>m just adding some data and retrieving it right from the main() function of the console app. Line <span class="integer">3</span> probably the only line that needs explanation. It<span class="error">’</span>s a call to the <span class="directive">static</span> method SetInitializer() on the <span class="directive">static</span> DbDatabase <span class="type">class</span> <span class="class">of</span> EF. The parameter is a <span class="keyword">new</span> instance of DropCreateDatabaseAlways&lt;MedContext&gt;. Creating <span class="local-variable">this</span> initializer with it<span class="error">’</span>s type parameter set to our MedContext tells the EF engine that it should always drop the database and recreate it, every time the app is run. This is part of EF<span class="error">’</span>s <span class="keyword">new</span> fluent <span class="type">interface</span>. Under <span class="class">almost</span> no circumstance would you actually use <span class="local-variable">this</span> initializer, but it<span class="error">’</span>s handy <span class="keyword">for</span> testing and playing around. This way you can iterate over your model getting a <span class="keyword">new</span> database <span class="keyword">for</span> each run.
 937
 938The rest of the function adds a Prescription object with two FilledScript objects, and saves it in the context. It then loops through the prescriptions and writes some info to the console about each. No rocket science there.
 939
 940
 941<span class="error">#</span><span class="error">#</span> Where did EF Create the Database?
 942
 943
 944One cool thing about EFCodeFirst is that you can leave off pretty much all the configuration information. We didn<span class="error">’</span>t tell EF anything about how or where to create the database. It came up with some reasonable defaults. If you open SSMS and connect to your instance of SQL Express, you can see the database it created. Here<span class="error">’</span>s a DB diagram in SSMS from what EF created:
 945
 946[![image](http:<span class="comment">//blog.efvincent.com/wp-content/uploads/2011/01/image_thumb5.png)](http://blog.efvincent.com/wp-content/uploads/2011/01/image5.png)</span>
 947
 948The database it created (<span class="integer">1</span>) is named according to the context that it stores, MedContext <span class="keyword">for</span> us. It created tables (<span class="integer">2</span> &amp; <span class="integer">3</span>) <span class="keyword">for</span> the entities we created, and to implement the one to many relationship, it added a foreign key to the FilledScripts table linking it to the Prescriptions table. There<span class="error">’</span>s always a DBA to disagree with an auto-generated schema, but in <span class="local-variable">this</span> simple <span class="keyword">case</span>, you must admit there<span class="error">’</span>s not a whole lot you could <span class="keyword">do</span> differently. If we select the records out of the database after our run you get the expected results:
 949
 950[![image](http:<span class="comment">//blog.efvincent.com/wp-content/uploads/2011/01/image_thumb6.png)](http://blog.efvincent.com/wp-content/uploads/2011/01/image6.png)</span>
 951
 952All of <span class="local-variable">this</span> was created by convention, and can also be overridden and specified explicitly using either attributes on the classes that make up the model, or by using EF<span class="error">’</span>s fluent API. This barely scratches the surface, but hopefully gets you interested. I<span class="error">’</span>ll cover EF in more depth in a future post, plus there<span class="error">’</span>s plenty of info out there already.
 953
 954
 955<span class="error">#</span><span class="error">#</span> Back to NuGet <span class="error">–</span> Removing a <span class="predefined-type">Package</span>
 956
 957
 958Ok, we<span class="error">’</span>ve seen how easy it is to add a <span class="keyword">package</span> <span class="namespace">like</span> <span class="namespace">EFCodeFirst</span> (<span class="namespace">and</span> <span class="namespace">how</span> <span class="namespace">cool</span> <span class="namespace">EF</span> <span class="namespace">itself</span> <span class="namespace">is</span>). <span class="namespace">NuGet</span> <span class="namespace">also</span> <span class="namespace">allows</span> <span class="namespace">you</span> <span class="namespace">to</span> <span class="namespace">remove</span> <span class="namespace">a</span> <span class="namespace">package</span> <span class="namespace">easily</span>. <span class="namespace">In</span> <span class="namespace">the</span> <span class="namespace">Package</span> <span class="namespace">Manager</span> <span class="namespace">Console</span> <span class="namespace">window</span>, <span class="namespace">issue</span> <span class="namespace">the</span> <span class="namespace">command</span>:
 959
 960</pre></td>
 961</tr></table>
 962</div>
 963<p>PM&gt; Uninstall-Package EFCodeFirst
 964Successfully removed ‘EFCodeFirst 0.8’ from ConsoleApplication2
 965Successfully uninstalled ‘EFCodeFirst 0.8’
 966~~~</p>
 967
 968<p>NuGet will remove all traces of the package from your project. For EFCodeFirst there’s not much to remove. But other packages are far more complicated, even pulling in prerequisite packages, and modifying the web or app.config. NuGet undoes all these changes when a package is removed.</p>
 969
 970<h2 id="try-it-yourself">Try it yourself!</h2>
 971
 972<p>One great thing about NuGet is how painless it makes trying out new things. You’re not fouling up your precious work machine with a bunch of installations. You can create a quick test project, add a bunch of things you’ve always wanted to try, and just blow it all away when you’re done. No evidence you’ve been <em>learning</em>.</p>
 973
 974<p>Ever want to try Fluent NHibernate but didn’t feel like dealing with all the crap that goes with tracking it down and installing it? How about Ninject, Castle, ELMAH, iTextSharp, Moq, or Prism? They’re all out there. Just NuGet them and start playing / learning.</p>
 975
 976<h2 id="what-else">What else?</h2>
 977
 978<p>I didn’t even mention the wizardy, non-console approach. Right click on your project, and select Add Library Package Reference… and you get a pretty UI that lets you click instead of type. But you’re a coder. You can type.</p>
 979
 980<p>Publishing your own package. You can create any package you want. Perhaps one that pulls in some of your favorite utility classes. Or perhaps you’ve got some corporate libraries and frameworks that you want to be able to incorporate using NuGet. You can create your own private or a corporate NuGet gallery. Or if you have something worth while, publish it up to the official NuGet gallery, it’s own to the public.</p>
 981
 982<p>I hope you’ve found this ramble of mine useful. Search around for more NuGet goodness. There are plenty of bloggers way more interesting then me publishing good information.</p>
 983
 984<p>Happy Coding!</p>
 985]]></content>
 986  </entry>
 987  
 988  <entry>
 989    <title type="html"><![CDATA[Open Source, MVC, MVVM, Entity Framework, NuGet, and More…]]></title>
 990    <link href="http://efvincent.github.io/blog/2011/01/12/open-source-nuget-and-more/"/>
 991    <updated>2011-01-12T08:53:31-05:00</updated>
 992    <id>http://efvincent.github.io/blog/2011/01/12/open-source-nuget-and-more</id>
 993    <content type="html"><![CDATA[<p><strong>Updated</strong>: see the <a href="http://blog.efvincent.com/nuget-geeky-goodness/">NuGet post</a></p>
 994
 995<p>The 2010 PDC was a few months ago. There was plenty of interesting and exciting tech news coming from the conference, but the one session that really sparked something with me was Scott Hanselman’s Presentation, <em><a href="http://www.hanselman.com/blog/PDC10BuildingABlogWithMicrosoftUnnamedPackageOfWebLove.aspx">ASP.NET + Packaging + Open Source = Crazy Delicious</a></em>. Officially, I was mining PDC for Azure and Windows Identity Foundation material for the project I was (and still am) working on. But I <em>love</em> Hanselman’s presentation style; is stuff is always entertaining, stimulating, and <strong>packed</strong> with information. This one was no exception.
 996<!-- more -->
 997In a nutshell, the presentation described several different new and pre-release technologies mashed up together into a single very technical demo. All of these techs are interesting, and over the last couple of months I’ve dived into several, if not all of them and I’ve learned a whole lot. I plan on writing about these techs, mostly because when I do I end up learning a lot in the process. But also so I can promote some of these in some small way. In the coming [random time period] I’ll be posting on:</p>
 998
 999<p><a href="http://nuget.codeplex.com/"><strong>NuGet</strong></a> – <em>a free, open source developer focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development</em>. (that’s quoted from the Codeplex page). It’s way cooler then it sounds… you’ll see.</p>
1000
1001<p><strong><a href="http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx">Entity Framework Magic Unicorn Edition</a></strong> – That’s what Hanselman called it, it’s got one of those painful Microsoft names in real life, but Magic Unicorn sounds better. It’s Entity Framework 4, the Code Only Entity Framework. EF without boxes and lines. It’s super cool and you’ll love it. Trust me.</p>
1002
1003<p><strong><a href="http://weblogs.asp.net/scottgu/archive/2010/12/10/announcing-asp-net-mvc-3-release-candidate-2.aspx">ASP.NET MVC</a> –</strong> Not bleeding edge, it’s been around for a couple of years now. Version 3 is in beta right now, and it’s getting tight. Time to take a look. Even if you’re not going to use it at work next week, it’s important to start thinking about web development done differently then ASP.NET (some would argue, correctly).</p>
1004
1005<p><strong>MVVM Pattern in WPF and Silverlight</strong> – Ok this one is not from Hanselman’s talk, but at the same time I’ve been looking at all the other tech I’ve had to dive into some WPF UI work for a project, and I figured I’d see what all the chatter was about with MVVM. I’ve spent so many years server side, I decided to approach UI with a clean slate.</p>
1006
1007<p>I’m sure there’ll be more. I’m rehabbing from knee replacement surgery, so I have some extra time behind the keyboard. Now – <a href="http://blog.efvincent.com/nuget-geeky-goodness/">on to NuGet</a>.</p>
1008]]></content>
1009  </entry>
1010  
1011</feed>