PageRenderTime 96ms CodeModel.GetById 18ms RepoModel.GetById 5ms app.codeStats 0ms

/blog/categories/c-number/atom.xml

https://github.com/efvincent/efvincent.github.io
XML | 1011 lines | 808 code | 198 blank | 5 comment | 0 complexity | f3d678342ee7a3bfb0e4ea953609e5f5 MD5 | raw file
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <feed xmlns="http://www.w3.org/2005/Atom">
  3. <title><![CDATA[Category: C# | Curried Functions]]></title>
  4. <link href="http://efvincent.github.io/blog/categories/c-number/atom.xml" rel="self"/>
  5. <link href="http://efvincent.github.io/"/>
  6. <updated>2014-08-18T13:03:44-04:00</updated>
  7. <id>http://efvincent.github.io/</id>
  8. <author>
  9. <name><![CDATA[Eric F. Vincent]]></name>
  10. </author>
  11. <generator uri="http://octopress.org/">Octopress</generator>
  12. <entry>
  13. <title type="html"><![CDATA[DI Constructor Injection, Bootstrapping]]></title>
  14. <link href="http://efvincent.github.io/blog/2011/06/24/di-bootstrap/"/>
  15. <updated>2011-06-24T02:07:31-04:00</updated>
  16. <id>http://efvincent.github.io/blog/2011/06/24/di-bootstrap</id>
  17. <content type="html"><![CDATA[<h2 id="constructor-injection">Constructor Injection</h2>
  18. <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.
  19. <!-- more -->
  20. There are several benefits to this particular method of injection; the most obvious is that in a well designed system the dependencies of a class are clearly visible in the constructor. In the <a href="http://blog.efvincent.com/practical-di-101">DI 101</a> post a data provider was defined like this:</p>
  21. <div><table class="CodeRay"><tr>
  22. <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
  23. <a href="#n2" name="n2">2</a>
  24. <a href="#n3" name="n3">3</a>
  25. <a href="#n4" name="n4">4</a>
  26. <a href="#n5" name="n5">5</a>
  27. <a href="#n6" name="n6">6</a>
  28. <a href="#n7" name="n7">7</a>
  29. <a href="#n8" name="n8">8</a>
  30. <a href="#n9" name="n9">9</a>
  31. <strong><a href="#n10" name="n10">10</a></strong>
  32. <a href="#n11" name="n11">11</a>
  33. <a href="#n12" name="n12">12</a>
  34. <a href="#n13" name="n13">13</a>
  35. <a href="#n14" name="n14">14</a>
  36. </pre></td>
  37. <td class="code"><pre><span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
  38. <span class="directive">private</span> readonly IIdentService _identService;
  39. <span class="directive">private</span> readonly ILogService _logSvc;
  40. <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;();
  41. <span class="directive">public</span> DevDataProvider(IIdentService identService, ILogService logSvc) {
  42. <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>);
  43. <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>);
  44. _identService = identService;
  45. _logSvc = logSvc;
  46. }
  47. <span class="comment">// Remaining implementation omitted for brevity</span>
  48. }
  49. </pre></td>
  50. </tr></table>
  51. </div>
  52. <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>
  53. <p>There are other advantages to using constructor injection. Should the list of dependencies get too long, say longer than four parameters, youve got a code smell that perhaps the class is doing too much, violating the single responsibility principal.</p>
  54. <h2 id="bootstrapping">Bootstrapping</h2>
  55. <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>
  56. <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>
  57. <h2 id="bootstrapping-a-console-application">Bootstrapping a Console Application</h2>
  58. <p>Depending on the type of application youre 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 Seemans Dependency Injection</a> book, published by Manning)</em>.</p>
  59. <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>
  60. <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>
  61. <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>
  62. <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>
  63. <h2 id="only-directly-reference-the-di-container-in-the-bootstrapper">Only Directly Reference the DI Container in the Bootstrapper</h2>
  64. <p>This is an important point, and if you get nothing else from this post, understand this.</p>
  65. <ul>
  66. <li>The DI container is configured in the composition root (Main() in this case)</li>
  67. <li>The DI container is used to resolve or build the App</li>
  68. <li>The app is then run to do the work</li>
  69. </ul>
  70. <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>
  71. <h4 id="weve-taken-on-a-dependency-to-the-di-container-itself">Weve taken on a dependency to the DI Container itself</h4>
  72. <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 dont 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>
  73. <p>In any kind of a significant application the apps 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>
  74. <h4 id="were-hiding-a-dependency-inside-the-app">Were hiding a dependency inside the App</h4>
  75. <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 dont want to see lines like this buried in the methods of the classes:</p>
  76. <div><table class="CodeRay"><tr>
  77. <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
  78. <a href="#n2" name="n2">2</a>
  79. <a href="#n3" name="n3">3</a>
  80. <a href="#n4" name="n4">4</a>
  81. <a href="#n5" name="n5">5</a>
  82. <a href="#n6" name="n6">6</a>
  83. <a href="#n7" name="n7">7</a>
  84. <a href="#n8" name="n8">8</a>
  85. </pre></td>
  86. <td class="code"><pre><span class="comment">// Anti-pattern - don't use DI container except</span>
  87. <span class="comment">// in composition root</span>
  88. var dal = <span class="predefined-type">Container</span>.Resolve&lt;IDataAccessService&gt;();
  89. <span class="comment">// And defintely don't do this</span>
  90. var dal = <span class="keyword">new</span> SqlDataAccessService(connectString);
  91. </pre></td>
  92. </tr></table>
  93. </div>
  94. <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>
  95. <h3 id="bootstrapping-in-other-application-types">Bootstrapping in other Application Types</h3>
  96. <p>Other types of apps have different places for bootstrapping and application roots. Unlike a console app, an ASP.NET MVC 3 application isnt 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>
  97. <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 dont 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>
  98. <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, theres 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>
  99. <h3 id="di-unfriendly-application-types">DI Unfriendly Application Types</h3>
  100. <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>
  101. <p>There are other mechanisms for implementing DI patterns in this case, but theyre sub-optimal. Again Id refer you to <a href="http://www.manning.com/seemann/">Mark Seemans 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>
  102. <h3 id="in-summary">In Summary</h3>
  103. <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 youll be shocked you ever wrote applications <em>without</em> some degree of dependency injection. Yea its that good for you.</p>
  104. ]]></content>
  105. </entry>
  106. <entry>
  107. <title type="html"><![CDATA[A Taste of Dependency Injection, Testing, and Mocking]]></title>
  108. <link href="http://efvincent.github.io/blog/2011/05/27/di-mock/"/>
  109. <updated>2011-05-27T20:28:53-04:00</updated>
  110. <id>http://efvincent.github.io/blog/2011/05/27/di-mock</id>
  111. <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>
  112. <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>
  113. <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>
  114. <p><strong>ILogService</strong> describes a simple logging service. The ConsoleLogService implementation prints logs to the console.</p>
  115. <!-- more -->
  116. <p>### Dependency Injection &amp;Testing</p>
  117. <p>For this post Ive 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>
  118. <div><table class="CodeRay"><tr>
  119. <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
  120. <a href="#n2" name="n2">2</a>
  121. <a href="#n3" name="n3">3</a>
  122. <a href="#n4" name="n4">4</a>
  123. <a href="#n5" name="n5">5</a>
  124. <a href="#n6" name="n6">6</a>
  125. <a href="#n7" name="n7">7</a>
  126. <a href="#n8" name="n8">8</a>
  127. <a href="#n9" name="n9">9</a>
  128. <strong><a href="#n10" name="n10">10</a></strong>
  129. <a href="#n11" name="n11">11</a>
  130. <a href="#n12" name="n12">12</a>
  131. <a href="#n13" name="n13">13</a>
  132. <a href="#n14" name="n14">14</a>
  133. </pre></td>
  134. <td class="code"><pre><span class="directive">static</span> IContainer afContainer;
  135. [ClassInitialize]
  136. <span class="directive">public</span> <span class="directive">static</span> <span class="type">void</span> TestInit(TestContext ctx) {
  137. var idSvc = A.Fake&lt;IIdentService&gt;();
  138. A.CallTo(() =&gt; idSvc.GetCurrentUserName())
  139. .Returns(<span class="string"><span class="delimiter">&quot;</span><span class="content">FAKE-ID</span><span class="delimiter">&quot;</span></span>);
  140. var bldr = <span class="keyword">new</span> ContainerBuilder();
  141. bldr.RegisterInstance(idSvc);
  142. bldr.RegisterInstance(A.Fake&lt;ILogService&gt;());
  143. bldr.RegisterType&lt;DevDataProvider&gt;().As&lt;IDataProvider&gt;();
  144. afContainer = bldr.Build();
  145. }
  146. </pre></td>
  147. </tr></table>
  148. </div>
  149. <p>The test class has a static DI container instance, initialized in the class initializer. Im 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>
  150. <p>I then register the fake ident service as well as a fake log service. For the log service, we dont 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>
  151. <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 providers dependencies for a log service and an identity service with the fakes we built.</p>
  152. <div><table class="CodeRay"><tr>
  153. <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
  154. <a href="#n2" name="n2">2</a>
  155. <a href="#n3" name="n3">3</a>
  156. <a href="#n4" name="n4">4</a>
  157. <a href="#n5" name="n5">5</a>
  158. <a href="#n6" name="n6">6</a>
  159. <a href="#n7" name="n7">7</a>
  160. <a href="#n8" name="n8">8</a>
  161. </pre></td>
  162. <td class="code"><pre>[TestMethod()]
  163. <span class="directive">public</span> <span class="type">void</span> GetCurrentEmployeeTest() {
  164. 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> };
  165. var dal = afContainer.Resolve&lt;IDataProvider&gt;();
  166. dal.AddEmployee(e);
  167. var result = dal.GetCurrentEmployee();
  168. Assert.AreEqual(e.WindowsUsername, result.WindowsUsername);
  169. }
  170. </pre></td>
  171. </tr></table>
  172. </div>
  173. <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 weve 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>
  174. <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>
  175. ]]></content>
  176. </entry>
  177. <entry>
  178. <title type="html"><![CDATA[Practical Dependency Injection 101]]></title>
  179. <link href="http://efvincent.github.io/blog/2011/05/27/practical-di-101/"/>
  180. <updated>2011-05-27T13:08:27-04:00</updated>
  181. <id>http://efvincent.github.io/blog/2011/05/27/practical-di-101</id>
  182. <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 VBers who read C# can benefit just as much), whove heard of DI but havent gotten around to figuring out how it fits in their day to day.</p>
  183. <!-- more -->
  184. <p>### What is Dependency Injection</p>
  185. <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 were 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 youre already writing decent code and have good fundamentals, but are not using DI patterns, youve got the opportunity to take a leap forward.</p>
  186. <p>How does DI reduce help reduce coupling? The easiest way to describe it is by diving directly into an example.</p>
  187. <h3 id="example-scenario">Example Scenario</h3>
  188. <p>Well 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. Its pretty common to see stuff like this happening in-house with line of business applications.</p>
  189. <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 wed replace this as development continued with a provider that leverages persistent storage later.</p>
  190. <p>Heres the base level example program with no consideration for dependency injection:</p>
  191. <div><table class="CodeRay"><tr>
  192. <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
  193. <a href="#n2" name="n2">2</a>
  194. <a href="#n3" name="n3">3</a>
  195. <a href="#n4" name="n4">4</a>
  196. <a href="#n5" name="n5">5</a>
  197. <a href="#n6" name="n6">6</a>
  198. <a href="#n7" name="n7">7</a>
  199. <a href="#n8" name="n8">8</a>
  200. <a href="#n9" name="n9">9</a>
  201. <strong><a href="#n10" name="n10">10</a></strong>
  202. <a href="#n11" name="n11">11</a>
  203. <a href="#n12" name="n12">12</a>
  204. <a href="#n13" name="n13">13</a>
  205. <a href="#n14" name="n14">14</a>
  206. <a href="#n15" name="n15">15</a>
  207. <a href="#n16" name="n16">16</a>
  208. <a href="#n17" name="n17">17</a>
  209. <a href="#n18" name="n18">18</a>
  210. <a href="#n19" name="n19">19</a>
  211. <strong><a href="#n20" name="n20">20</a></strong>
  212. <a href="#n21" name="n21">21</a>
  213. <a href="#n22" name="n22">22</a>
  214. <a href="#n23" name="n23">23</a>
  215. <a href="#n24" name="n24">24</a>
  216. <a href="#n25" name="n25">25</a>
  217. <a href="#n26" name="n26">26</a>
  218. <a href="#n27" name="n27">27</a>
  219. <a href="#n28" name="n28">28</a>
  220. <a href="#n29" name="n29">29</a>
  221. <strong><a href="#n30" name="n30">30</a></strong>
  222. <a href="#n31" name="n31">31</a>
  223. <a href="#n32" name="n32">32</a>
  224. <a href="#n33" name="n33">33</a>
  225. <a href="#n34" name="n34">34</a>
  226. <a href="#n35" name="n35">35</a>
  227. <a href="#n36" name="n36">36</a>
  228. <a href="#n37" name="n37">37</a>
  229. <a href="#n38" name="n38">38</a>
  230. <a href="#n39" name="n39">39</a>
  231. <strong><a href="#n40" name="n40">40</a></strong>
  232. <a href="#n41" name="n41">41</a>
  233. <a href="#n42" name="n42">42</a>
  234. <a href="#n43" name="n43">43</a>
  235. <a href="#n44" name="n44">44</a>
  236. <a href="#n45" name="n45">45</a>
  237. <a href="#n46" name="n46">46</a>
  238. <a href="#n47" name="n47">47</a>
  239. <a href="#n48" name="n48">48</a>
  240. <a href="#n49" name="n49">49</a>
  241. <strong><a href="#n50" name="n50">50</a></strong>
  242. <a href="#n51" name="n51">51</a>
  243. <a href="#n52" name="n52">52</a>
  244. <a href="#n53" name="n53">53</a>
  245. <a href="#n54" name="n54">54</a>
  246. <a href="#n55" name="n55">55</a>
  247. <a href="#n56" name="n56">56</a>
  248. <a href="#n57" name="n57">57</a>
  249. <a href="#n58" name="n58">58</a>
  250. <a href="#n59" name="n59">59</a>
  251. <strong><a href="#n60" name="n60">60</a></strong>
  252. <a href="#n61" name="n61">61</a>
  253. </pre></td>
  254. <td class="code"><pre><span class="type">class</span> <span class="class">Program</span> {
  255. <span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
  256. <span class="comment">// ** Without using an DI Container approach **</span>
  257. <span class="comment">// Create a new provider aka data access layer</span>
  258. var dal = <span class="keyword">new</span> DevDataProvider();
  259. <span class="comment">// New up an employee that's supposed to represent the currently logged in user</span>
  260. var e = <span class="keyword">new</span> Employee() {
  261. 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>,
  262. EmployeeId = <span class="string"><span class="delimiter">&quot;</span><span class="content">0001</span><span class="delimiter">&quot;</span></span>,
  263. FName = <span class="string"><span class="delimiter">&quot;</span><span class="content">Eric</span><span class="delimiter">&quot;</span></span>,
  264. LName = <span class="string"><span class="delimiter">&quot;</span><span class="content">Vincent</span><span class="delimiter">&quot;</span></span>
  265. };
  266. <span class="comment">// Add it to the data access layer</span>
  267. dal.AddEmployee(e);
  268. <span class="comment">// See if the dal can find the current user</span>
  269. e = dal.GetCurrentEmployee();
  270. Console.WriteLine(
  271. <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);
  272. <span class="comment">// End</span>
  273. Console.Write(<span class="string"><span class="delimiter">&quot;</span><span class="content">Press any key...</span><span class="delimiter">&quot;</span></span>);
  274. Console.ReadKey(<span class="predefined-constant">true</span>);
  275. }
  276. }
  277. <span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> {
  278. <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;();
  279. <span class="directive">public</span> Employee GetCurrentEmployee() {
  280. var emp = EmployeeStore.FirstOrDefault(
  281. e =&gt; e.WindowsUsername.Equals(GetCurrentUserName(), StringComparison.OrdinalIgnoreCase));
  282. <span class="keyword">return</span> emp;
  283. }
  284. <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
  285. EmployeeStore.Add(e);
  286. }
  287. <span class="directive">public</span> IQueryable&lt;Employee&gt; Employees() {
  288. <span class="keyword">return</span> EmployeeStore.AsQueryable();
  289. }
  290. <span class="directive">private</span> <span class="directive">static</span> string GetCurrentUserName() {
  291. var wu = WindowsIdentity.GetCurrent();
  292. <span class="keyword">return</span> wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
  293. }
  294. }
  295. <span class="directive">public</span> <span class="type">class</span> <span class="class">Employee</span> {
  296. <span class="directive">public</span> string WindowsUsername { get; set; }
  297. <span class="directive">public</span> string EmployeeId { get; set; }
  298. <span class="directive">public</span> string FName { get; set; }
  299. <span class="directive">public</span> string LName { get; set; }
  300. }
  301. </pre></td>
  302. </tr></table>
  303. </div>
  304. <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? Lets look at the coupling here what classes are dependent on what other classes?</p>
  305. <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>
  306. <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 isnt the best idea, but this is blog post code created to check out dependency injection, so deal with that for the moment.</p>
  307. <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, wed 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>
  308. <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 its calling the Windows API to get the current username. This makes that method harder to than it needs to be.</p>
  309. <h3 id="step-one--leveraging-interfaces">Step One Leveraging Interfaces</h3>
  310. <p>In this version, weve 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 were testing, we can create a fake service that provides a predictable answer, and is therefore easier to test.</p>
  311. <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 wont want to use the current Windows Identity, we may want to use user information from the http context.</p>
  312. <div><table class="CodeRay"><tr>
  313. <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
  314. <a href="#n2" name="n2">2</a>
  315. <a href="#n3" name="n3">3</a>
  316. <a href="#n4" name="n4">4</a>
  317. <a href="#n5" name="n5">5</a>
  318. <a href="#n6" name="n6">6</a>
  319. <a href="#n7" name="n7">7</a>
  320. <a href="#n8" name="n8">8</a>
  321. <a href="#n9" name="n9">9</a>
  322. <strong><a href="#n10" name="n10">10</a></strong>
  323. <a href="#n11" name="n11">11</a>
  324. <a href="#n12" name="n12">12</a>
  325. <a href="#n13" name="n13">13</a>
  326. <a href="#n14" name="n14">14</a>
  327. <a href="#n15" name="n15">15</a>
  328. <a href="#n16" name="n16">16</a>
  329. <a href="#n17" name="n17">17</a>
  330. <a href="#n18" name="n18">18</a>
  331. <a href="#n19" name="n19">19</a>
  332. <strong><a href="#n20" name="n20">20</a></strong>
  333. <a href="#n21" name="n21">21</a>
  334. <a href="#n22" name="n22">22</a>
  335. <a href="#n23" name="n23">23</a>
  336. <a href="#n24" name="n24">24</a>
  337. <a href="#n25" name="n25">25</a>
  338. <a href="#n26" name="n26">26</a>
  339. <a href="#n27" name="n27">27</a>
  340. <a href="#n28" name="n28">28</a>
  341. <a href="#n29" name="n29">29</a>
  342. <strong><a href="#n30" name="n30">30</a></strong>
  343. <a href="#n31" name="n31">31</a>
  344. <a href="#n32" name="n32">32</a>
  345. <a href="#n33" name="n33">33</a>
  346. <a href="#n34" name="n34">34</a>
  347. <a href="#n35" name="n35">35</a>
  348. <a href="#n36" name="n36">36</a>
  349. <a href="#n37" name="n37">37</a>
  350. <a href="#n38" name="n38">38</a>
  351. <a href="#n39" name="n39">39</a>
  352. <strong><a href="#n40" name="n40">40</a></strong>
  353. <a href="#n41" name="n41">41</a>
  354. <a href="#n42" name="n42">42</a>
  355. <a href="#n43" name="n43">43</a>
  356. <a href="#n44" name="n44">44</a>
  357. <a href="#n45" name="n45">45</a>
  358. <a href="#n46" name="n46">46</a>
  359. <a href="#n47" name="n47">47</a>
  360. </pre></td>
  361. <td class="code"><pre><span class="comment">// Interface defining an identity service</span>
  362. <span class="directive">public</span> <span class="type">interface</span> <span class="class">IIdentService</span> {
  363. string GetCurrentUserName();
  364. }
  365. <span class="comment">// Implementation of an identity service that returns the current</span>
  366. <span class="comment">// logged in windows username</span>
  367. <span class="directive">public</span> <span class="type">class</span> <span class="class">WindowsIdentService</span> : IIdentService {
  368. <span class="directive">public</span> string GetCurrentUserName() {
  369. var wu = WindowsIdentity.GetCurrent();
  370. <span class="keyword">return</span> wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
  371. }
  372. }
  373. <span class="comment">// Interface defining a data provider service</span>
  374. <span class="directive">public</span> <span class="type">interface</span> <span class="class">IDataProvider</span> {
  375. Employee GetCurrentEmployee();
  376. <span class="type">void</span> AddEmployee(Employee e);
  377. IQueryable&lt;Employee&gt; Employees();
  378. }
  379. <span class="comment">// Our development data provider now implements the interface</span>
  380. <span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
  381. <span class="directive">private</span> readonly IIdentService _identService;
  382. <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;();
  383. <span class="directive">public</span> DevDataProvider(IIdentService identService) {
  384. <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>);
  385. _identService = identService;
  386. }
  387. <span class="directive">public</span> Employee GetCurrentEmployee() {
  388. var emp = EmployeeStore.FirstOrDefault(
  389. e =&gt; e.WindowsUsername.Equals(
  390. _identService.GetCurrentUserName(),
  391. StringComparison.OrdinalIgnoreCase));
  392. <span class="keyword">return</span> emp;
  393. }
  394. <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
  395. EmployeeStore.Add(e);
  396. }
  397. <span class="directive">public</span> IQueryable&lt;Employee&gt; Employees() {
  398. <span class="keyword">return</span> EmployeeStore.AsQueryable();
  399. }
  400. }
  401. </pre></td>
  402. </tr></table>
  403. </div>
  404. <p>Were 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 weve made creation of the DevDataProvider a bit more complex, as we need to supply the new instance with an IIdentityService instance.</p>
  405. <p>~~~C#
  406. // Create a new ident service, required for the DAL
  407. IIdentService identSvc = new WindowsIdentService();</p>
  408. <p>// Create a new DAL
  409. IDataProvider dal = new DevDataProvider(identSvc);
  410. ~~~</p>
  411. <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>
  412. <p>The complexity of constructing instances increases when we add a simple logging service which logs information or errors messages.</p>
  413. <p>~~~C#
  414. // Interface defining a logging service
  415. public interface ILogService {
  416. void LogInfo(string msg, params object[] args);
  417. void LogError(string msg, params object[] args);
  418. }</p>
  419. <p>// Implementation of a console logging service
  420. public class ConsoleLogger : ILogService {
  421. public void LogInfo(string msg, params object[] args) {
  422. Console.WriteLine(
  423. {0} INFO: {1}, DateTime.Now,
  424. string.Format(msg, args));
  425. }</p>
  426. <pre><code>public void LogError(string msg, params object[] args) {
  427. Console.WriteLine(
  428. "{0} ERROR: {1}", DateTime.Now,
  429. string.Format(msg, args));
  430. } } ~~~
  431. </code></pre>
  432. <p>The ILogService is implemented by a simple console logger. Now both the WindowsIdentService and the DevDataProvider can leverage the logger. Theyre both modified to have ILogService instance injected via their respective constructors.</p>
  433. <div><table class="CodeRay"><tr>
  434. <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
  435. <a href="#n2" name="n2">2</a>
  436. <a href="#n3" name="n3">3</a>
  437. <a href="#n4" name="n4">4</a>
  438. <a href="#n5" name="n5">5</a>
  439. <a href="#n6" name="n6">6</a>
  440. <a href="#n7" name="n7">7</a>
  441. <a href="#n8" name="n8">8</a>
  442. <a href="#n9" name="n9">9</a>
  443. <strong><a href="#n10" name="n10">10</a></strong>
  444. <a href="#n11" name="n11">11</a>
  445. <a href="#n12" name="n12">12</a>
  446. <a href="#n13" name="n13">13</a>
  447. <a href="#n14" name="n14">14</a>
  448. <a href="#n15" name="n15">15</a>
  449. <a href="#n16" name="n16">16</a>
  450. <a href="#n17" name="n17">17</a>
  451. <a href="#n18" name="n18">18</a>
  452. <a href="#n19" name="n19">19</a>
  453. <strong><a href="#n20" name="n20">20</a></strong>
  454. <a href="#n21" name="n21">21</a>
  455. <a href="#n22" name="n22">22</a>
  456. <a href="#n23" name="n23">23</a>
  457. <a href="#n24" name="n24">24</a>
  458. <a href="#n25" name="n25">25</a>
  459. <a href="#n26" name="n26">26</a>
  460. <a href="#n27" name="n27">27</a>
  461. <a href="#n28" name="n28">28</a>
  462. <a href="#n29" name="n29">29</a>
  463. <strong><a href="#n30" name="n30">30</a></strong>
  464. <a href="#n31" name="n31">31</a>
  465. <a href="#n32" name="n32">32</a>
  466. <a href="#n33" name="n33">33</a>
  467. <a href="#n34" name="n34">34</a>
  468. <a href="#n35" name="n35">35</a>
  469. <a href="#n36" name="n36">36</a>
  470. <a href="#n37" name="n37">37</a>
  471. <a href="#n38" name="n38">38</a>
  472. <a href="#n39" name="n39">39</a>
  473. <strong><a href="#n40" name="n40">40</a></strong>
  474. <a href="#n41" name="n41">41</a>
  475. <a href="#n42" name="n42">42</a>
  476. <a href="#n43" name="n43">43</a>
  477. <a href="#n44" name="n44">44</a>
  478. <a href="#n45" name="n45">45</a>
  479. <a href="#n46" name="n46">46</a>
  480. <a href="#n47" name="n47">47</a>
  481. <a href="#n48" name="n48">48</a>
  482. <a href="#n49" name="n49">49</a>
  483. </pre></td>
  484. <td class="code"><pre><span class="comment">// Implementation of an identity service that returns the current</span>
  485. <span class="comment">// logged in windows username</span>
  486. <span class="directive">public</span> <span class="type">class</span> <span class="class">WindowsIdentService</span> : IIdentService {
  487. <span class="directive">private</span> readonly ILogService _logSvc;
  488. <span class="directive">public</span> WindowsIdentService(ILogService logSvc) {
  489. <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>);
  490. _logSvc = logSvc;
  491. }
  492. <span class="directive">public</span> string GetCurrentUserName() {
  493. var wu = WindowsIdentity.GetCurrent();
  494. var un = wu == <span class="predefined-constant">null</span> ? string.Empty : wu.Name;
  495. _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);
  496. <span class="keyword">return</span> un;
  497. }
  498. }
  499. <span class="comment">// Our development data provider now implements the interface</span>
  500. <span class="directive">public</span> <span class="type">class</span> <span class="class">DevDataProvider</span> : IDataProvider {
  501. <span class="directive">private</span> readonly IIdentService _identService;
  502. <span class="directive">private</span> readonly ILogService _logSvc;
  503. <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;();
  504. <span class="directive">public</span> DevDataProvider(IIdentService identService, ILogService logSvc) {
  505. <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>);
  506. <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>);
  507. _identService = identService;
  508. _logSvc = logSvc;
  509. }
  510. <span class="directive">public</span> Employee GetCurrentEmployee() {
  511. var un = _identService.GetCurrentUserName();
  512. var emp = EmployeeStore.FirstOrDefault(
  513. e =&gt; e.WindowsUsername.Equals(un,
  514. StringComparison.OrdinalIgnoreCase));
  515. <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);
  516. <span class="keyword">return</span> emp;
  517. }
  518. <span class="directive">public</span> <span class="type">void</span> AddEmployee(Employee e) {
  519. EmployeeStore.Add(e);
  520. _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);
  521. }
  522. <span class="directive">public</span> IQueryable&lt;Employee&gt; Employees() {
  523. <span class="keyword">return</span> EmployeeStore.AsQueryable();
  524. }
  525. }
  526. </pre></td>
  527. </tr></table>
  528. </div>
  529. <p>Now the services are getting more robust and theyre 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>
  530. <div><table class="CodeRay"><tr>
  531. <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
  532. <a href="#n2" name="n2">2</a>
  533. <a href="#n3" name="n3">3</a>
  534. <a href="#n4" name="n4">4</a>
  535. <a href="#n5" name="n5">5</a>
  536. <a href="#n6" name="n6">6</a>
  537. <a href="#n7" name="n7">7</a>
  538. <a href="#n8" name="n8">8</a>
  539. <a href="#n9" name="n9">9</a>
  540. <strong><a href="#n10" name="n10">10</a></strong>
  541. <a href="#n11" name="n11">11</a>
  542. <a href="#n12" name="n12">12</a>
  543. </pre></td>
  544. <td class="code"><pre><span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
  545. <span class="comment">// ** Without using an DI Container approach **</span>
  546. <span class="comment">// Create a new logging service, required for uh.. everything</span>
  547. ILogService consoleLog = <span class="keyword">new</span> ConsoleLogger();
  548. <span class="comment">// Create a new ident service, required for the DAL</span>
  549. IIdentService identSvc = <span class="keyword">new</span> WindowsIdentService(consoleLog);
  550. <span class="comment">// Create a new DAL</span>
  551. IDataProvider dal = <span class="keyword">new</span> DevDataProvider(identSvc, consoleLog);
  552. </pre></td>
  553. </tr></table>
  554. </div>
  555. <p>Finally were at the point where we can see the benefit of an dependency injection container. One thing about DI containers is that theyre already written. Several mature, robust, open-source DI containers exist. Well use AutoFac, because thats what Ive 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>
  556. <pre><code>// Create a singleton dependency injection container
  557. private static readonly IContainer Container = ConfigureContainer();
  558. // Configure the container
  559. static IContainer ConfigureContainer() {
  560. // This is how AutoFac works. Other DI containers have similar
  561. // mechanisms for configuring the container
  562. var bld = new ContainerBuilder();
  563. // Register the types that implement the interfaces that are required
  564. // for injection. Note that we have robust control over lifetime, in
  565. // this case ILogService and IIdentService will be singletons, and
  566. // IDataProvider will provide a new instance each time it's requested
  567. bld.RegisterType&lt;ConsoleLogger&gt;().As&lt;ILogService&gt;().SingleInstance();
  568. bld.RegisterType&lt;WindowsIdentService&gt;().As&lt;IIdentService&gt;().SingleInstance();
  569. bld.RegisterType&lt;DevDataProvider&gt;().As&lt;IDataProvider&gt;();
  570. return bld.Build();
  571. }
  572. static void Main(string[] args) {
  573. // ** Using an IoC Container approach **
  574. var dal = Container.Resolve&lt;IDataProvider&gt;();
  575. </code></pre>
  576. <p>Weve 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 theres 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>
  577. <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>
  578. <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; theres plenty of material out there.</p>
  579. <p>I hope this example was helpful. Next post Ill extend this sample by looking at testing, and mock objects, and how DI injection can make testing far easier.</p>
  580. <p>Source code samples can be found at this <a href="https://bitbucket.org/efvincent/blog-post-dependency-injection-101">bitbucket repository</a>.</p>
  581. <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>
  582. ]]></content>
  583. </entry>
  584. <entry>
  585. <title type="html"><![CDATA[NuGet Galleries of Geeky Goodness.]]></title>
  586. <link href="http://efvincent.github.io/blog/2011/01/12/nuget-geeky-goodness/"/>
  587. <updated>2011-01-12T18:27:26-05:00</updated>
  588. <id>http://efvincent.github.io/blog/2011/01/12/nuget-geeky-goodness</id>
  589. <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 Hanselmans <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 Ill 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. Ill see if I can make a meaningful contribution.</p>
  590. <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>
  591. <!-- more -->
  592. <h2 id="installation">Installation</h2>
  593. <p>NuGet, like dozens of other useful add-ins, is available through the Visual Studio Extension Manager, reached under _Tools Extension Manager. _</p>
  594. <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>
  595. <p>From the Extension Manager choose (1) the online gallery, and then (2) search for NuGet. A restart of Visual Studio is required.</p>
  596. <h2 id="the-nuget-package-manager-console">The NuGet Package Manager Console</h2>
  597. <p>NuGet has two user interfaces. Theres 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>
  598. <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>
  599. <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>
  600. <p>List-Packages remote</p>
  601. <p>There are a lot of them, and since the console is PowerShell we can take advantage of a PowerShell grid display:</p>
  602. <table>
  603. <tbody>
  604. <tr>
  605. <td>List-Packages remote</td>
  606. <td>out-GridView</td>
  607. </tr>
  608. </tbody>
  609. </table>
  610. <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>
  611. <h2 id="installing-and-removing-packages">Installing and Removing Packages</h2>
  612. <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>
  613. <p>Lets 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 well use it here for a quick example. Normally, if you want to try out something like a new version of Entity Framework, theres downloading, installing, shaving the chicken, bla bla bla that youve got to do. Not with NuGet. NuGet can effectively __xcopy deploy it into our project.</p>
  614. <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>
  615. <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>
  616. <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>
  617. <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>
  618. <p>Checking the properties of the reference to EntityFramework, you can see that its not installed to the GAC, its 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 theres information out there you can dig up if youre so inclined.</p>
  619. <h2 id="using-entity-framework">Using Entity Framework</h2>
  620. <p>Now that weve got it installed, lets quickly use EFCodeFirst just to prove its working. For this example, youll need SQL Server installed (there are other options, but one thing at a time). Ive got Express which works fine. In another post Ill 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>
  621. <p>EFCodeFirst allows you to build POCO objects and use them to build a DB. Lets build a quick model. There are a few examples floating around modeling blog posts and comments, so lets <em>not</em> do that. Lets do (super simple) prescriptions and medications. Its on my mind because Im recovering from knee surgery. This code is entered directly into the Program.cs source file for this example.</p>
  622. <div><table class="CodeRay"><tr>
  623. <td class="line-numbers"><pre><a href="#n1" name="n1">1</a>
  624. <a href="#n2" name="n2">2</a>
  625. <a href="#n3" name="n3">3</a>
  626. <a href="#n4" name="n4">4</a>
  627. <a href="#n5" name="n5">5</a>
  628. <a href="#n6" name="n6">6</a>
  629. <a href="#n7" name="n7">7</a>
  630. <a href="#n8" name="n8">8</a>
  631. <a href="#n9" name="n9">9</a>
  632. <strong><a href="#n10" name="n10">10</a></strong>
  633. <a href="#n11" name="n11">11</a>
  634. <a href="#n12" name="n12">12</a>
  635. <a href="#n13" name="n13">13</a>
  636. <a href="#n14" name="n14">14</a>
  637. <a href="#n15" name="n15">15</a>
  638. <a href="#n16" name="n16">16</a>
  639. <a href="#n17" name="n17">17</a>
  640. <a href="#n18" name="n18">18</a>
  641. <a href="#n19" name="n19">19</a>
  642. <strong><a href="#n20" name="n20">20</a></strong>
  643. <a href="#n21" name="n21">21</a>
  644. <a href="#n22" name="n22">22</a>
  645. <a href="#n23" name="n23">23</a>
  646. <a href="#n24" name="n24">24</a>
  647. <a href="#n25" name="n25">25</a>
  648. <a href="#n26" name="n26">26</a>
  649. <a href="#n27" name="n27">27</a>
  650. <a href="#n28" name="n28">28</a>
  651. <a href="#n29" name="n29">29</a>
  652. <strong><a href="#n30" name="n30">30</a></strong>
  653. <a href="#n31" name="n31">31</a>
  654. <a href="#n32" name="n32">32</a>
  655. <a href="#n33" name="n33">33</a>
  656. <a href="#n34" name="n34">34</a>
  657. <a href="#n35" name="n35">35</a>
  658. <a href="#n36" name="n36">36</a>
  659. <a href="#n37" name="n37">37</a>
  660. <a href="#n38" name="n38">38</a>
  661. <a href="#n39" name="n39">39</a>
  662. <strong><a href="#n40" name="n40">40</a></strong>
  663. <a href="#n41" name="n41">41</a>
  664. <a href="#n42" name="n42">42</a>
  665. <a href="#n43" name="n43">43</a>
  666. <a href="#n44" name="n44">44</a>
  667. <a href="#n45" name="n45">45</a>
  668. <a href="#n46" name="n46">46</a>
  669. <a href="#n47" name="n47">47</a>
  670. <a href="#n48" name="n48">48</a>
  671. <a href="#n49" name="n49">49</a>
  672. <strong><a href="#n50" name="n50">50</a></strong>
  673. <a href="#n51" name="n51">51</a>
  674. <a href="#n52" name="n52">52</a>
  675. <a href="#n53" name="n53">53</a>
  676. <a href="#n54" name="n54">54</a>
  677. <a href="#n55" name="n55">55</a>
  678. <a href="#n56" name="n56">56</a>
  679. <a href="#n57" name="n57">57</a>
  680. <a href="#n58" name="n58">58</a>
  681. <a href="#n59" name="n59">59</a>
  682. <strong><a href="#n60" name="n60">60</a></strong>
  683. <a href="#n61" name="n61">61</a>
  684. <a href="#n62" name="n62">62</a>
  685. <a href="#n63" name="n63">63</a>
  686. <a href="#n64" name="n64">64</a>
  687. <a href="#n65" name="n65">65</a>
  688. <a href="#n66" name="n66">66</a>
  689. <a href="#n67" name="n67">67</a>
  690. <a href="#n68" name="n68">68</a>
  691. <a href="#n69" name="n69">69</a>
  692. <strong><a href="#n70" name="n70">70</a></strong>
  693. <a href="#n71" name="n71">71</a>
  694. <a href="#n72" name="n72">72</a>
  695. <a href="#n73" name="n73">73</a>
  696. <a href="#n74" name="n74">74</a>
  697. <a href="#n75" name="n75">75</a>
  698. <a href="#n76" name="n76">76</a>
  699. <a href="#n77" name="n77">77</a>
  700. <a href="#n78" name="n78">78</a>
  701. <a href="#n79" name="n79">79</a>
  702. <strong><a href="#n80" name="n80">80</a></strong>
  703. <a href="#n81" name="n81">81</a>
  704. <a href="#n82" name="n82">82</a>
  705. <a href="#n83" name="n83">83</a>
  706. <a href="#n84" name="n84">84</a>
  707. <a href="#n85" name="n85">85</a>
  708. <a href="#n86" name="n86">86</a>
  709. <a href="#n87" name="n87">87</a>
  710. <a href="#n88" name="n88">88</a>
  711. <a href="#n89" name="n89">89</a>
  712. <strong><a href="#n90" name="n90">90</a></strong>
  713. </pre></td>
  714. <td class="code"><pre><span class="directive">public</span> <span class="type">class</span> <span class="class">Prescription</span> {
  715. <span class="directive">public</span> <span class="type">int</span> Id { get; set; }
  716. <span class="directive">public</span> string MedName { get; set; }
  717. <span class="directive">public</span> string Directions { get; set; }
  718. <span class="directive">public</span> <span class="type">int</span> Quantity { get; set; }
  719. <span class="directive">public</span> <span class="type">int</span> Refills { get; set; }
  720. <span class="directive">public</span> <span class="type">int</span> RefillsRemaining { get; set; }
  721. <span class="directive">public</span> ICollection&lt;FilledScript&gt; FilledScripts { get; set; }
  722. }
  723. <span class="directive">public</span> <span class="type">class</span> <span class="class">FilledScript</span> {
  724. <span class="directive">public</span> <span class="type">int</span> Id { get; set; }
  725. <span class="directive">public</span> Prescription Script { get; set; }
  726. <span class="directive">public</span> DateTime Filled { get; set; }
  727. <span class="directive">public</span> <span class="type">int</span> Doses { get; set; }
  728. }
  729. <span class="directive">public</span> <span class="type">class</span> <span class="class">MedContext</span> : DbContext {
  730. <span class="directive">public</span> DbSet&lt;Prescription&gt; Prescriptions { get; set; }
  731. <span class="directive">public</span> DbSet&lt;FilledScript&gt; FilledScripts { get; set; }
  732. }
  733. <span class="error">`</span><span class="error">`</span><span class="error">`</span>
  734. We 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.
  735. The _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:
  736. ~~~java
  737. <span class="directive">static</span> <span class="type">void</span> Main(string<span class="type">[]</span> args) {
  738. DbDatabase.SetInitializer(<span class="keyword">new</span> DropCreateDatabaseAlways&lt;MedContext&gt;());
  739. var ctx = <span class="keyword">new</span> MedContext();
  740. var p = <span class="keyword">new</span> Prescription() {
  741. MedName = <span class="string"><span class="delimiter">&quot;</span><span class="content">Vicoden</span><span class="delimiter">&quot;</span></span>,
  742. 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>,
  743. Quantity = <span class="integer">60</span>,
  744. Refills = <span class="integer">2</span>,
  745. RefillsRemaining = <span class="integer">1</span>,
  746. FilledScripts = <span class="keyword">new</span><span class="type">[]</span> {
  747. <span class="keyword">new</span> FilledScript() {
  748. Filled = DateTime.Parse(<span class="string"><span class="delimiter">&quot;</span><span class="content">12/28/2010</span><span class="delimiter">&quot;</span></span>),
  749. Doses = <span class="integer">0</span>
  750. },
  751. <span class="keyword">new</span> FilledScript() {
  752. Filled = DateTime.Parse(<span class="string"><span class="delimiter">&quot;</span><span class="content">1/12/2011</span><span class="delimiter">&quot;</span></span>),
  753. Doses = <span class="integer">48</span>
  754. }
  755. }
  756. };
  757. ctx.Prescriptions.Add(p);
  758. ctx.SaveChanges();
  759. foreach (var script in ctx.Prescriptions) {
  760. 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>,
  761. script.MedName,
  762. script.FilledScripts.Count(),
  763. script.FilledScripts.Sum(fs =&gt; fs.Doses));
  764. }
  765. 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>);
  766. Console.ReadKey(<span class="predefined-constant">true</span>);
  767. }
  768. <span class="error">`</span><span class="error">`</span><span class="error">`</span>
  769. For <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.
  770. The 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.
  771. <span class="error">#</span><span class="error">#</span> Where did EF Create the Database?
  772. One 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:
  773. [![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>
  774. The 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:
  775. [![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>
  776. All 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.
  777. <span class="error">#</span><span class="error">#</span> Back to NuGet <span class="error"></span> Removing a <span class="predefined-type">Package</span>
  778. Ok, 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>:
  779. </pre></td>
  780. </tr></table>
  781. </div>
  782. <p>PM&gt; Uninstall-Package EFCodeFirst
  783. Successfully removed EFCodeFirst 0.8 from ConsoleApplication2
  784. Successfully uninstalled EFCodeFirst 0.8
  785. ~~~</p>
  786. <p>NuGet will remove all traces of the package from your project. For EFCodeFirst theres 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>
  787. <h2 id="try-it-yourself">Try it yourself!</h2>
  788. <p>One great thing about NuGet is how painless it makes trying out new things. Youre not fouling up your precious work machine with a bunch of installations. You can create a quick test project, add a bunch of things youve always wanted to try, and just blow it all away when youre done. No evidence youve been <em>learning</em>.</p>
  789. <p>Ever want to try Fluent NHibernate but didnt 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? Theyre all out there. Just NuGet them and start playing / learning.</p>
  790. <h2 id="what-else">What else?</h2>
  791. <p>I didnt 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 youre a coder. You can type.</p>
  792. <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 youve 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, its own to the public.</p>
  793. <p>I hope youve 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>
  794. <p>Happy Coding!</p>
  795. ]]></content>
  796. </entry>
  797. <entry>
  798. <title type="html"><![CDATA[Open Source, MVC, MVVM, Entity Framework, NuGet, and More]]></title>
  799. <link href="http://efvincent.github.io/blog/2011/01/12/open-source-nuget-and-more/"/>
  800. <updated>2011-01-12T08:53:31-05:00</updated>
  801. <id>http://efvincent.github.io/blog/2011/01/12/open-source-nuget-and-more</id>
  802. <content type="html"><![CDATA[<p><strong>Updated</strong>: see the <a href="http://blog.efvincent.com/nuget-geeky-goodness/">NuGet post</a></p>
  803. <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 Hanselmans 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> Hanselmans presentation style; is stuff is always entertaining, stimulating, and <strong>packed</strong> with information. This one was no exception.
  804. <!-- more -->
  805. In 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 Ive dived into several, if not all of them and Ive 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] Ill be posting on:</p>
  806. <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>. (thats quoted from the Codeplex page). Its way cooler then it sounds youll see.</p>
  807. <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> Thats what Hanselman called it, its got one of those painful Microsoft names in real life, but Magic Unicorn sounds better. Its Entity Framework 4, the Code Only Entity Framework. EF without boxes and lines. Its super cool and youll love it. Trust me.</p>
  808. <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, its been around for a couple of years now. Version 3 is in beta right now, and its getting tight. Time to take a look. Even if youre not going to use it at work next week, its important to start thinking about web development done differently then ASP.NET (some would argue, correctly).</p>
  809. <p><strong>MVVM Pattern in WPF and Silverlight</strong> Ok this one is not from Hanselmans talk, but at the same time Ive been looking at all the other tech Ive had to dive into some WPF UI work for a project, and I figured Id see what all the chatter was about with MVVM. Ive spent so many years server side, I decided to approach UI with a clean slate.</p>
  810. <p>Im sure therell be more. Im 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>
  811. ]]></content>
  812. </entry>
  813. </feed>