<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Solutionizing .NET &#187; Dependency Injection</title>
	<atom:link href="http://solutionizing.net/tag/dependency-injection/feed/" rel="self" type="application/rss+xml" />
	<link>http://solutionizing.net</link>
	<description>Random thoughts on custom development in SharePoint.</description>
	<lastBuildDate>Sat, 12 May 2012 03:45:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='solutionizing.net' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Solutionizing .NET &#187; Dependency Injection</title>
		<link>http://solutionizing.net</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://solutionizing.net/osd.xml" title="Solutionizing .NET" />
	<atom:link rel='hub' href='http://solutionizing.net/?pushpress=hub'/>
		<item>
		<title>SPTDD: On Good Vs. Testable Code</title>
		<link>http://solutionizing.net/2009/02/20/sptdd-on-good-vs-testable-code/</link>
		<comments>http://solutionizing.net/2009/02/20/sptdd-on-good-vs-testable-code/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 11:44:21 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[Object Model]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[SPTDD]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Typemock Isolator]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=438</guid>
		<description><![CDATA[First, my position on SharePoint Test Driven Development: I don&#8217;t currently use it. I got a free Isolator license (thanks!) that I have yet to install (sorry!). Just like everyone else, I&#8217;m trying to figure out where TDD fits in the context of SharePoint. Any assertions in this post about TDD are based on my [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=438&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>First, my position on SharePoint Test Driven Development: I don&#8217;t currently use it. I got a <a title="Isolator for SharePoint" href="http://solutionizing.net/2008/11/25/isolator-for-sharepoint/">free Isolator license</a> (thanks!) that I have yet to install (sorry!). Just like everyone else, I&#8217;m trying to figure out where TDD fits in the context of SharePoint. Any assertions in this post about TDD are based on my current understanding, which is incomplete at best.</p>
<p>This post is in response to a post by Eric Shupps: <a href="http://www.binarywave.com/blogs/eshupps/Lists/Posts/Post.aspx?ID=179">SPTDD: SharePoint and Test Driven Development, Part One</a>. He has a lot to say, so let&#8217;s start with this assertion:</p>
<blockquote><p>&#8230;in order to get real value from TDD in SharePoint you must <strong>already know how to write good code</strong>. All the unit tests in the world won&#8217;t change this fact. And the only way to learn how to write good code is to do it over and over again, gathering knowledge along the way from those who have gone before you. This leads the the fundamental problem with TDD as a methodology &#8211; it doesn&#8217;t teach developers how to write good code; rather, it teaches them how to write <em>testable</em> code.</p></blockquote>
<p>I agree with the differentiation between <em>good</em> and <em>testable</em> code, but I think Eric underestimates the value of testable code in relation to its goodness. For reference, let&#8217;s bring in how his example code &#8220;should be written&#8221;:</p>
<pre>private SPListItemCollection GetListItems(string Url, string ListName)
{
    SPListItemCollection coll = null;
    try
    {
        if (Url != String.Empty &amp;&amp; ListName != String.Empty)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        try
                        {
                            SPList list = web.Lists[ListName];
                            if (list.Items.Count &gt; 0)
                            {
                                coll = list.Items;
                            }
                        }
                        catch (System.Exception ex)
                        {
                            LogError(ex.Message);
                        }
                    }
                }
            });
        }
    }
    catch (System.Exception ex)
    {
        LogError(ex.Message);
    }
    return coll;
}</pre>
<p>I know &#8220;good code&#8221; is subjective, but this method has some real problems:</p>
<ul>
<li><code>SP*</code> objects should not be passed out of a RWEP block.</li>
<li><code>SP*</code> objects should not be used after their parent <code>SPWeb</code> has been disposed.</li>
<li>Each call to <code>list.Items</code> will execute a new query. Instead, store it to a variable or use <code>list.ItemCount</code>.</li>
</ul>
<p>These issues have nothing to do with testability. They&#8217;re simply not good SharePoint code. But TDD wouldn&#8217;t fix them, so for the purpose of argument let&#8217;s use this code instead (essentially Eric&#8217;s original plus error handling):</p>
<pre>private SPListItemCollection GetListItems(string Url, string ListName)
{
    SPListItemCollection coll = null;
    try
    {
        if (Url != String.Empty &amp;&amp; ListName != String.Empty)
        {
            SPSite site = new SPSite(Url);
            SPWeb web = site.OpenWeb();
            try
            {
                SPList list = web.Lists[ListName];
                SPListItemCollection items = list.Items;
                if (items.Count &gt; 0)
                {
                    coll = items;
                }
            }
            catch (System.Exception ex)
            {
                LogError(ex.Message);
            }
        }
    }
    catch (System.Exception ex)
    {
        LogError(ex.Message);
    }
    return coll;
}</pre>
<p>So supposing we used TDD, a method like this would have been created based on tests written to verify the following:</p>
<ul>
<li>If <code>Url</code> or <code>ListName</code> are empty, return <code>null</code>.</li>
<li>If <code>Url</code> or <code>ListName</code> are <code>null</code>, use them anyway and log the resulting exception.</li>
<li>Create <code>SPSite</code> and <code>SPWeb</code> that the caller needs to remember to dispose.</li>
<li>If the list has no items, return <code>null</code>, otherwise return all items.</li>
<li>If anything goes wrong, log the exception and return <code>null</code>.</li>
</ul>
<p>I would guess this isn&#8217;t exactly what Eric intended the method to do (at least regarding <code>null</code> arguments), but the hypothetical tests drove the TDD implementation; a different set of tests would have led to a more correct version of the method. Herein lies the problem with critiquing TDD based on code developed without tests—TDD would likely yield a different implementation!</p>
<h3>Abstraction and Dependency Injection = Artifacts?</h3>
<p>I also take issue with this passage:</p>
<blockquote><p>Look closely &#8211; the code itself satisfies all the test requirements without requiring any level of abstraction, dependency injection, nUnit, or other such artifices.</p></blockquote>
<p>[Irony: artifice - n. Cleverness or skill; ingenuity.]</p>
<p>Regarding satisfaction of the requirements, the obvious question is: How do you know? Without a test, you don&#8217;t, and to think you do just because you &#8220;already know how to write good code&#8221; is more naive than thinking unit-tested SharePoint code is bulletproof. Case in point: <code>null</code> arguments. But more importantly, when did abstraction and dependency injection become TDD things? These are basic programming principles, completely independent from TDD or SharePoint! Just because we&#8217;re developing against a specific (and complicated) API doesn&#8217;t mean the general best practices don&#8217;t apply. We should be .NET developers first, SharePoint developers second. Even without using TDD, I submit that your particular code could benefit quite a bit from dependency injection:</p>
<pre>private SPListItemCollection GetListItems(SPWeb web, string listName, SPQuery query)
{
    if (web == null || string.IsNullOrEmpty(listName))
        return null;
    SPListItemCollection coll = null;
    try
    {
        SPList list = web.Lists[listName];
        SPListItemCollection items = query == null ? list.Items : list.GetItems(query);
        if (items.Count &gt; 0)
        {
            coll = items;
        }
    }
    catch (Exception ex)
    {
        LogError(ex.Message);
    }
    return coll;
}</pre>
<p>Instead of creating an <code>SPWeb</code> that needs to be disposed by the caller, we just accept one that the caller should already be handling. Instead of always using <code>list.Items</code> (<a title="Best Practices: Common Coding Issues When Using the SharePoint Object Model" href="http://msdn.microsoft.com/en-us/library/bb687949.aspx#WorkingWithFoldersLists">not recommended</a>), we accept an optional <code>SPQuery</code>. The method has a clear purpose, doesn&#8217;t have the <code>new SPSite</code> to handle, works just as well with an elevated <code>SPWeb</code>, etc. It&#8217;s simply a better design, with improved testability being more of a side benefit than the main goal. I can&#8217;t say for sure, but I would guess a TDDed version (given the right requirements) would be similar.</p>
<h3>On Mocking</h3>
<p>Again, I haven&#8217;t found time to try out Isolator so I can&#8217;t really speak to the actual practice of testing mocked objects; however, it seems to me that it would be useful to verify that, <strong>given certain assumptions about a SharePoint environment</strong>, tests pass. If I can copy/paste a few lines of code to fake an SPWeb, with or without a named list, with or without list items, this seems like it would be much easier than actually creating and deleting lists and items to verify that my code behaves accordingly. Then as long as I&#8217;m in an environment that matches an assumption I tested, I&#8217;m assured the code will work as expected. Isolator seems to enable this sort of test with relative ease, at which point the general arguments for (and against) testing and TDD can be applied to SharePoint without much translation.</p>
<p>All that said, thanks to Eric for posting his thoughts to spark a more public discussion. Also, check out <a href="http://www.21apps.com/blog/">Andrew Woodward</a>&#8216;s <a title="SharePoint and TDD – The other view" href="http://www.21apps.com/sharepoint/sharepoint-and-tdd-the-other-view/">first rebuttal</a> and other posts on SharePoint and TDD (particularly <a title="Unit Testing SharePoint Solutions - Getting into the SharePoint Object Model" href="http://www.21apps.com/tdd-getting-into-sharepoint-om/">Unit Testing SharePoint Solutions &#8211; Getting into the SharePoint Object Model</a>).</p>
<br /> Tagged: Dependency Injection, SPTDD, TDD, Testing, Typemock Isolator <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/438/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=438&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/02/20/sptdd-on-good-vs-testable-code/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>ServerContext and Dependency Injection</title>
		<link>http://solutionizing.net/2009/02/14/servercontext-and-dependency-injection/</link>
		<comments>http://solutionizing.net/2009/02/14/servercontext-and-dependency-injection/#comments</comments>
		<pubDate>Sat, 14 Feb 2009 08:59:19 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[Object Model]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[ServerContext]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=418</guid>
		<description><![CDATA[I was reviewing some code today and came across a perfect case study for Dependency Injection. It also required another peak under the hood of Microsoft.Office.Server.ServerContext, the results of which I thought might be worth sharing. From MSDN,  ServerContext &#8220;provides run-time methods for shared services in Microsoft Office SharePoint Server 2007.&#8221; If you&#8217;re not familiar [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=418&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I was reviewing some code today and came across a perfect case study for <a href="http://en.wikipedia.org/wiki/Dependency_injection">Dependency Injection</a>. It also required another peak under the hood of <a title="ServerContext Class (Microsoft.Office.Server)" href="http://msdn.microsoft.com/en-us/library/microsoft.office.server.servercontext.aspx">Microsoft.Office.Server.ServerContext</a>, the results of which I thought might be worth sharing.</p>
<p>From MSDN,  <code>ServerContext</code> &#8220;provides run-time methods for shared services in Microsoft Office SharePoint Server 2007.&#8221; If you&#8217;re not familiar with Shared Service Providers, <a title="The SharePoint Farmer's Almanac" href="http://msmvps.com/blogs/shane/default.aspx">Shane Young</a> has a <a title="What is a Shared Service Provider?" href="http://msmvps.com/blogs/shane/archive/2007/06/29/what-is-a-shared-service-provider.aspx">concise overview</a> or check out <a href="http://blog.tedpattison.net/default.aspx">Ted Pattison</a>&#8216;s <a title="New Dev-Centric Features In Office SharePoint Server Keep Your Apps Rolling" href="http://msdn.microsoft.com/en-us/magazine/cc163560.aspx">developer overview</a> on MSDN. The SSP APIs span several namespaces:</p>
<ul>
<li>Microsoft.Office.Excel.Server</li>
<li>Microsoft.Office.Server.ApplicationRegistry (Business Data Catalog)</li>
<li>Microsoft.Office.Server.Audience</li>
<li>Microsoft.Office.Server.Search</li>
<li>Microsoft.Office.Server.UserProfiles (includes My Sites)</li>
</ul>
<p>The entry point to all of these APIs is ultimately a <code>ServerContext</code> object, made available through several static methods and properties:</p>
<ul>
<li><strong>ServerContext.Default</strong><br />
Returns a new instance for the local farm&#8217;s default provider.</li>
<li><strong>ServerContext.Current</strong><br />
Returns <code>ServerContext.GetContext(HttpContext.Current)</code>.</li>
<li><strong>ServerContext.GetContext(HttpContext httpContext)</strong><br />
Returns a shared ServerContext instance for the given request context. The provider is determined first through the microsoft.office.server/sharedService section in Web.config, and from the context <code>WebApplication</code> if that fails.</li>
<li><strong>ServerContext.GetContext(WebApplication webApplication)</strong><br />
Returns a new instance for the web application&#8217;s provider or the farm&#8217;s default provider if one is not specified.</li>
<li><strong>ServerContext.GetContext(SPSite site)</strong><br />
Returns <code>ServerContext.GetContext(site.WebApplication)</code>.</li>
<li><strong>ServerContext.GetContext(String sharedResourceProviderName)</strong><br />
Returns a new instance for the named provider if it exists, either in the local farm or its parent.</li>
</ul>
<p>These details inform some simple usage guidelines:</p>
<ol>
<li>If you have an <code>HttpContext</code>, use the shared instance from <code>GetContext(HttpContext)</code> or <code>ServerContext.Current</code>.</li>
<li>If you need a specific SSP, use an overload of <code>GetContext()</code>.</li>
<li>Else, use <code>ServerContext.Default</code>.</li>
</ol>
<h2>Code Review</h2>
<p>The code I was reviewing today was replacing this&#8230;</p>
<pre>SearchContext.GetContext(SPContext.Current.Site)</pre>
<p>&#8230;with this&#8230;</p>
<pre>SearchContext.GetContext(ServerContext.Default)</pre>
<p>&#8230;to support use of the service in a non-web context. We&#8217;re currently working with a single SSP, so <code>Default</code> should be sufficient; however, we can do better. First, the change in question had to be made in several places. For maintainability, it makes more sense to define a field or property to represent the context wherever we need it. Second, by using <code>ServerContext.Default</code> we&#8217;re missing out on the benefits of the shared instance provided for an <code>HttpContext</code>, which we usually have.</p>
<h2>Dependency Injection</h2>
<p>The <a title="TDD Design Starter Kit - Dependency Inversion Principle " href="http://codebetter.com/blogs/jeremy.miller/articles/129543.aspx">Dependency Inversion Principle</a> suggests that we should decouple the source of our <code>ServerContext</code> object from how its consumption. What would that look like here? Well the simplest approach is constructor injection:</p>
<pre>private ServerContext { get; set; }
public MyService(ServerContext context)
{
    this.ServerContext = context;
}</pre>
<p>This is the purest form of DI in that the class knows nothing about where the <code>ServerContext</code> came from, but it&#8217;s often practical to &#8220;cheat&#8221; and expose a nicer interface. In my case, I chose to supplement that constructor with two others:</p>
<pre>public MyService() : this(ServerContext.Default) {}

public MyService(HttpContext httpContext)
       : this(ServerContext.GetContext(httpContext) {}</pre>
<p>Now my web part can just call <code>MyService(this.Context)</code> and we still have a convenient default constructor for use in PowerShell. Because everything should be usable from PowerShell. This same idea can be applied to a number of common SharePoint tasks, particularly anywhere you&#8217;re using <code>SPContext.Current</code>, with benefits including improved reusability, maintainability and <a title="Permanent Link to TDD in SharePoint - Step 2 Implementing DI" href="http://www.21apps.com/sharepoint/tdd-with-di-step2/">testability</a>.</p>
<br /> Tagged: Dependency Injection, ServerContext <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/418/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/418/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/418/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/418/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/418/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/418/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/418/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/418/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/418/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/418/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/418/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/418/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/418/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/418/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=418&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/02/14/servercontext-and-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
	</channel>
</rss>
