<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" media="screen" href="/styles/xslt/rss.xslt"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:c9="http://channel9.msdn.com">
<channel>
	<title>Channel 9 - Entries tagged with Singleton</title>
    <atom:link rel="self" type="application/rss+xml" href="http://channel9.msdn.com/Tags/singleton/RSS"></atom:link>
    <itunes:summary></itunes:summary>
    <itunes:author>Microsoft</itunes:author>
    <itunes:subtitle></itunes:subtitle>
    <image>
      <url>http://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.png</url>
      <title>Channel 9 - Entries tagged with Singleton</title>
      <link>http://channel9.msdn.com/Tags/singleton</link>
    </image>
    <itunes:image href=""></itunes:image>
    <itunes:category text="Technology"></itunes:category>
    <description>Channel 9 keeps you up to date with the latest news and behind the scenes info from Microsoft that developers love to keep up with. From LINQ to SilverLight – Watch videos and hear about all the cool technologies coming and the people behind them.</description>
    <link>http://channel9.msdn.com/Tags/singleton</link>
    <language>en</language>
    <pubDate>Tue, 21 May 2013 09:20:43 GMT</pubDate>
    <lastBuildDate>Tue, 21 May 2013 09:20:43 GMT</lastBuildDate>
    <generator>Rev9</generator>
    <c9:totalResults>6</c9:totalResults>
    <c9:pageCount>1</c9:pageCount>
    <c9:pageSize>25</c9:pageSize>
  <item>
      <title>Extreme ASP.NET Makeover: Disentangling Our Tangled Web-Overview - Refactoring</title>
      <description><![CDATA[
<h2>A Topsy-Turvy World</h2>
<p>The constructor signature for AuthorizationChecker now looks like this:</p>
<pre>public AuthorizationChecker(    ISettingsStorageProviderV30 settingsProvider,     IAuthTools authTools,     IAclEvaluator aclEvaluator) { ... }</pre>
<br>
<p>We can clearly see that AuthorizationChecker depends on implementations of ISettingsStorageProviderV30, IAuthTools, and IAclEvalator, but we are not concerned with the actual implementations. This is the dependency inversion principle at work.</p>
<p><i>&quot;High-level modules should not depend on low-level modules. Both should depend on abstractions.&quot;</i> – Robert C. Martin (<a shape="rect" href="http://objectmentor.com/resources/articles/dip.pdf" shape="rect">http://objectmentor.com/resources/articles/dip.pdf</a>)</p>
<p>In this case, AuthorizationChecker and AuthTools don’t depend on each other, but depend on the abstraction provided by IAuthTools. The same is true for AuthorizationChecker’s other two dependencies, ISettingsStorageProviderV30 and IAclEvaluator.</p>
<p>We have decoupled AuthorizationChecker from its dependencies. The question remains that AuthorizationChecker still needs these dependencies supplied at run-time to actually be able to execute. The simplest way to supply these dependences as default implementations
 via AuthorizationChecker's parameterless constructor:</p>
<pre>public AuthorizationChecker() :     this(Settings.Instance.Provider,         new AuthTools(), new AclEvaluator()) {}</pre>
<br>
<h2>Of Containers and Castles</h2>
<p>A more flexible way to supply dependencies is to use an Inversion of Control container, such as
<a shape="rect" href="http://castleproject.org/container/index.html" shape="rect">
Castle Windsor</a>. Castle Windsor is a set of assemblies that we reference from our code. We simply register all of our dependencies in the container and then ask the container for an implementation. The container walks the dependency chain, creates objects
 in the correct order, supplying dependencies as it creates objects further up the dependency chain until it can finally return us a fully constructed object. Consider the following code:</p>
<pre>var authorizationServices = IoC.Resolve&lt;IAuthorizationServices&gt;();</pre>
<br>
<p>The IoC is a static gateway class that provides an abstraction so that your code is not dependent on a particular IoC container for retrieving dependencies. It is similar in interface and approach to Microsoft’s
<a shape="rect" href="http://commonservicelocator.codeplex.com/" shape="rect">Common Service Locator</a> available on CodePlex. You can read more about the IoC static gateway in
<a shape="rect" href="http://msdn.microsoft.com/en-us/magazine/cc337885.aspx" shape="rect">
“Loosen Up: Tame Your Software Dependencies for More Flexible Apps”</a>.</p>
<p>In order for Castle Windsor to satisfy this request for an implementation of IAuthorizationServices, we’ll need to register the dependencies:</p>
<pre>var ssp = ProviderLoader.LoadSettingsStorageProvider(    WebConfigurationManager.AppSettings[&quot;SettingsStorageProvider&quot;]);container.Register(    AllTypes.FromAssembly(Assembly.GetExecutingAssembly())        .Where(x =&gt; x.Namespace.StartsWith(&quot;ScrewTurn.Wiki.Services&quot;))        .WithService.FirstInterface(),    Component.For&lt;IAclEvaluator&gt;().ImplementedBy&lt;AclEvaluator&gt;(),    Component.For&lt;ISettingsStorageProviderV30&gt;().Instance(ssp));</pre>
<br>
<p>This code is located in the ScrewTurn.Wiki.Core assembly. Rather than manually configuring each dependency individually, we use a convention-based approach whereby any types in the ScrewTurn.Wiki.Services namespace are registered via their first interface.
 This means that AuthorizationServices is registered as IAuthorizationServices, AuthTools is registered as IAuthTools, and similarly for other types in this namespace. This has the advantage that by placing services in the ScrewTurn.Wiki.Services namespace,
 they will automatically be registered in the container without requiring explicit configuration. Other classes can then take dependencies on these services simply by adding the appropriate interface to their own constructor.</p>
<p>AclEvaluator is located in the ScrewTurn.Wiki.AclEngine assembly. Since it is the only dependency in this assembly, we register it explicitly. There isn’t a great deal of value from having a separate assembly for ScrewTurn.Wiki.AclEngine and I would consider
 merging the AclEngine project into Core. AclEvaluator could then be placed in the ScrewTurn.Wiki.Services namespace and auto-registered like the other dependencies. For the moment, AclEvaluator serves as an example of how to explicitly configure dependencies
 in Castle Windsor.</p>
<p>ScrewTurn Wiki has code that dynamically loads a particular ISettingsStorageProviderV30 implementation specified by a fully qualified class name in a configuration file. Although we could use Castle Windsor’s configuration facilities to configure and load
 the appropriate assembly and implementation, that is not the current focus. We can leverage the existing loading mechanism by supplying Castle Windsor with a fully constructed instance via the Component.For&lt;T&gt;().Instance(obj) syntax.</p>
<p>Windsor provides many more configuration options, including overrides, parameters, XML configuration, and more. You can find a lot more information on configuration options in Castle Windsor in my article,
<a shape="rect" href="http://code-magazine.com/Article.aspx?quickid=0906051" shape="rect">
Bricks and Mortar: Building a Castle</a>.</p>
<p>Now that AuthorizationServices and all of its dependencies have been registered with the container, we can successfully resolve it from the container:</p>
<pre>var authorizationServices = IoC.Resolve&lt;IAuthorizationServices&gt;();</pre>
<br>
<p>To service this request, Windsor will look for an implementer of IAuthorizationServices, which is AuthorizationServices. Windsor will then examine AuthorizationServices constructor, specifically the constructor parameters:</p>
<pre>public AuthorizationServices(IAuthorizationChecker authorizationChecker) {    this.authorizationChecker = authorizationChecker;}</pre>
<br>
<p>Windsor will look to see if it has an implementation registered for IAuthorizationChecker, which it does in the form of AuthorizationChecker. Looking at AuthorizationChecker’s constructors:</p>
<pre>public AuthorizationChecker() : this(Settings.Instance.Provider,     new AuthTools(), new AclEvaluator()) {}public AuthorizationChecker(ISettingsStorageProviderV30 settingsProvider,     IAuthTools authTools, IAclEvaluator aclEvaluator) {&nbsp;&nbsp;&nbsp; ...}</pre>
<br>
<p>Windsor has two constructors to choose from. It starts from the constructor with the most overloads. It will see if it has implementations for all of the constructor parameters. (If it can’t find implementations for all constructor parameters, Windsor will
 attempt the next most overloaded constructor.) In this case, it will see that it needs to find an implementation for ISettingsStorageProviderV30, IAuthTools, and IAclEvaluator. Windsor has an instance of ISettingsStorageProviderV30 that we supplied to it earlier.
 It can also create instances of AuthTools and AclEvaluator because they have no further dependencies. Windsor passes the newly created AuthTools and AclEvaluator, as well as the pre-built ISettingsStorageProviderV30 to AuthorizationChecker’s constructor. Windsor
 then passes the newly created AuthorizationChecker to AuthorizationServices’ constructor. Finally, Windsor is able to pass back AuthorizationServices to satisfy the call to IoC.Resolve&lt;IAuthorizationServices&gt;.</p>
<p>Note that Windsor is responsible for managing the lifetime of objects registered in the container. Windsor’s default lifetime strategy is singleton. That means that multiple classes depending on IAuthorizationServices will all receive the same instance of
 AuthorizationServices. This instancing policy is easily changed on a per-service basis and includes options such as per-thread, per-Web-request, transient, and pooled. You can even create your own instancing policies if none of the built-in ones are appropriate.</p>
<p>With the container responsible for wiring dependencies between objects, we can remove the parameterless constructors as they are no longer required:</p>
<pre>public AuthorizationChecker(ISettingsStorageProviderV30 settingsProvider,     IAuthTools authTools, IAclEvaluator aclEvaluator) {     ...}</pre>
<br>
<p>If AuthorizationChecker required another dependency, we would simply declare that fact by adding another constructor parameter with a type of the required service interface. We would then create a concrete class in the ScrewTurn.Wiki.Services namespace that
 implements that service interface.</p>
<h2>Managing the Container</h2>
<p>I have seen many projects place all container configuration into a single XML or C# file. This is especially unwieldy if explicitly configuring dependencies individually, which is why I prefer the convention-over-configuration approach discussed above. By
 placing dependencies in certain assemblies and namespaces, they are automatically registered. (Note that the convention-over-configuration approach is not available with XML files, although XML files are useful for specifying deployment-time overrides if necessary.
 For more information about this technique, see <a shape="rect" href="http://code-magazine.com/Article.aspx?quickid=0906051" shape="rect">
Bricks and Mortar: Building a Castle</a>.) Placing all of our conventions in a single C# file can quickly become cumbersome as we have unrelated conventions bundled together.</p>
<p>Let’s take a look at an approach that allows us to separate our conventions into smaller, simpler classes. It all starts with the ApplicationBootstrapper, which is called during application startup:</p>
<pre>public void Configure() {    container = new WindsorContainer();    IoC.Initialize(new WindsorDependencyResolver(container));&nbsp;&nbsp;&nbsp; RegisterFacilityStartupTasks();&nbsp;&nbsp;&nbsp; ExecuteFacilityStartupTasks();&nbsp;&nbsp;&nbsp; RegisterContainerStartupTasks();&nbsp;&nbsp;&nbsp; ExecuteContainerStartupTasks();&nbsp;&nbsp;&nbsp; RegisterStartupTasks();&nbsp;&nbsp;&nbsp; ExecuteStartupTasks();}</pre>
<br>
<p>We start by creating a new WindsorContainer and using it to initialize the IoC static gateway. We then alternately register and execute FacilityStartup, ContainerStartup, and Startup tasks, as shown in
<b>Figure 2</b>.</p>
<p><b>Figure 2 Execute FacilityStartup, ContainerStartup, and Startup Tasks</b></p>
<pre>private void RegisterFacilityStartupTasks() {&nbsp;&nbsp;&nbsp; RegisterAllTypesBasedOn&lt;IFacilityStartupTask&gt;();}private void RegisterContainerStartupTasks() {    RegisterAllTypesBasedOn&lt;IContainerStartupTask&gt;();}private void RegisterStartupTasks() {&nbsp;&nbsp; RegisterAllTypesBasedOn&lt;IStartupTask&gt;();}private void RegisterAllTypesBasedOn&lt;T&gt;() {&nbsp;&nbsp;&nbsp; assembliesToScan.ForEach(assembly =&gt; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; container.Register(&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; AllTypes.FromAssembly(assembly)&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; .BasedOn&lt;T&gt;()&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .WithService.FirstInterface())&nbsp;&nbsp;&nbsp; );}</pre>
<br>
<p>The list of assemblies to scan for startup tasks is provided via AssemblyBootstrapper’s constructor and defaults to Assembly.GetExecutingAssembly if left unspecified. We look through each assembly for types implementing IFacilityStartupTask, IContainerStartupTask,
 and IStartupTask and register them against the appropriate interface. (Facilities are Windsor’s primary extension mechanism. You can use facilities to implement everything from automatic transaction management to logging to array parameter resolution and more.)
 Next, we need to execute each of the startup tasks:</p>
<pre>private void ExecuteFacilityStartupTasks() {&nbsp;&nbsp;&nbsp; var tasks = container.ResolveAll&lt;IFacilityStartupTask&gt;();&nbsp;&nbsp;&nbsp; tasks.ForEach(task =&gt; task.Execute(container));}private void ExecuteContainerStartupTasks() {&nbsp;&nbsp;&nbsp; var tasks = container.ResolveAll&lt;IContainerStartupTask&gt;();&nbsp;&nbsp;&nbsp; tasks.ForEach(task =&gt; task.Execute(container));}private void ExecuteStartupTasks() {&nbsp;&nbsp;&nbsp; var tasks = container.ResolveAll&lt;IStartupTask&gt;();&nbsp;&nbsp;&nbsp; tasks.ForEach(task =&gt; task.Execute());}</pre>
<br>
<p>Note that IFacilityStartupTask|IContainerStartupTask.Execute both take an IWindsorContainer, as their purpose is to configure the container. IStartupTask.Execute is to perform other types of initialization once the container is ready to be used and therefore
 doesn’t accept an IWindsorContainer.</p>
<p>The individual startup tasks are small and self-contained. For example, take a look at the ServiceRegistration class, which is responsible for registering application-related services:</p>
<pre>public class ServicesRegistration : IContainerStartupTask {&nbsp;&nbsp;&nbsp; public void Execute(IWindsorContainer container) {&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; container.Register(&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; AllTypes.FromAssembly(Assembly.GetExecutingAssembly())&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .Where(x =&gt; x.Namespace.StartsWith(&quot;ScrewTurn.Wiki.Services&quot;))&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .WithService.FirstInterface(),&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Component.For&lt;IAclEvaluator&gt;().ImplementedBy&lt;AclEvaluator&gt;()&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; );&nbsp;&nbsp;&nbsp; }}</pre>
<br>
<p>You can see the convention responsible for registering all services in the ScrewTurn.Wiki.Services namespace. There is also the extra configuration for the AclEvaluator. If we choose to combine the AclEngine project into Core, we could eliminate the extra
 configuration step for AclEvaluator.</p>
<p>We have a completely separate and independent IContainerStartupTask for Host and Provider registration:</p>
<pre>public class HostAndProviderRegistration : IContainerStartupTask {&nbsp;&nbsp;&nbsp; public void Execute(IWindsorContainer container) {&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; container.Register(&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Component.For&lt;IHostV30&gt;().ImplementedBy&lt;Host&gt;());&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; var ssp = ProviderLoader.LoadSettingsStorageProvider(            WebConfigurationManager.AppSettings[&quot;SettingsStorageProvider&quot;]);&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; container.Register(            Component.For&lt;ISettingsStorageProviderV30&gt;().Instance(ssp));&nbsp;&nbsp;&nbsp; }}</pre>
<br>
<p>As we break apart the “God object” that is the Host, we can modify its container registration in one place without affecting the registration of the services. If we need to perform additional unrelated container configuration, we create another class that
 implements the IFacilityStartupTask or IContainerStartupTask without affecting other configuration that is already taking place.</p>
<p>To wrap up, let’s refactor StartupTools.Startup() into a IStartupTask where it belongs:</p>
<h2>Conclusion</h2>
<p>Although it is not initially obvious, the ScrewTurn Wiki codebase suffers from dependency problems. Tight coupling of implementation classes caused by singletons and static classes result in a morass of objects, which is difficult to refactor. Dependency
 cycles between objects result in sensitive constructor and method orderings, which can result in unexpected NullReferenceExceptions after apparently innocuous changes to the code.</p>
<p>In this article, we have made dependencies obvious by changing them into constructor parameters and using an IoC container to wire together the dependencies. Using convention-over-configuration approaches eases the introduction of new functionality, without
 requiring explicit configuration. We have introduced a reusable ApplicationBootstrapper, whereby new startup tasks can be added as the application grows without modifying existing code. The resulting codebase should be more flexible and maintainable over time.</p>
<h2>Other videos from this article</h2>
<ul>
<li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Overview/" shape="rect">Overview</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Refactoring/" shape="rect">Refactoring</a>
</li></ul>
<p>Read the full article at <a shape="rect" href="http://msdn.microsoft.com/magazine/ee424155.aspx" shape="rect">
http://msdn.microsoft.com/magazine/ee424155.aspx</a> </p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Tags/singleton/RSS&WT.dl=0&WT.entryid=Entry:RSSView:ade3e4a857ed42b6909d9deb017702ef">]]></description>
      <comments>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Refactoring</comments>
      <itunes:summary>
A Topsy-Turvy World
The constructor signature for AuthorizationChecker now looks like this: 
public AuthorizationChecker(    ISettingsStorageProviderV30 settingsProvider,     IAuthTools authTools,     IAclEvaluator aclEvaluator) { ... }

We can clearly see that AuthorizationChecker depends on implementations of ISettingsStorageProviderV30, IAuthTools, and IAclEvalator, but we are not concerned with the actual implementations. This is the dependency inversion principle at work. 
&amp;quot;High-level modules should not depend on low-level modules. Both should depend on abstractions.&amp;quot; – Robert C. Martin (http://objectmentor.com/resources/articles/dip.pdf) 
In this case, AuthorizationChecker and AuthTools don’t depend on each other, but depend on the abstraction provided by IAuthTools. The same is true for AuthorizationChecker’s other two dependencies, ISettingsStorageProviderV30 and IAclEvaluator. 
We have decoupled AuthorizationChecker from its dependencies. The question remains that AuthorizationChecker still needs these dependencies supplied at run-time to actually be able to execute. The simplest way to supply these dependences as default implementations
 via AuthorizationChecker&#39;s parameterless constructor: 
public AuthorizationChecker() :     this(Settings.Instance.Provider,         new AuthTools(), new AclEvaluator()) {}

Of Containers and Castles
A more flexible way to supply dependencies is to use an Inversion of Control container, such as

Castle Windsor. Castle Windsor is a set of assemblies that we reference from our code. We simply register all of our dependencies in the container and then ask the container for an implementation. The container walks the dependency chain, creates objects
 in the correct order, supplying dependencies as it creates objects further up the dependency chain until it can finally return us a fully constructed object. Consider the following code: 
var authorizationServices = IoC.Resolve&amp;lt;IAuthorizationS</itunes:summary>
      <itunes:duration>896</itunes:duration>
      <link>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Refactoring</link>
      <pubDate>Tue, 01 Sep 2009 00:10:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Refactoring</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/100/487028_100x75.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/220/487028_220x165.jpg" height="165" width="220"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/ch9/8/2/0/7/8/4/RefactoringStartupTools_320_ch9.png" height="240" width="320"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/ch9/8/2/0/7/8/4/RefactoringStartupTools_512_ch9.png" height="384" width="512"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/ch9/8/2/0/7/8/4/RefactoringStartupTools_85_ch9.png" height="64" width="85"></media:thumbnail>
      <media:group>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/8/2/0/7/8/4/RefactoringStartupTools_2MB_ch9.wmv" expression="full" duration="896" fileSize="35996878" type="video/x-ms-wmv" medium="video"></media:content>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/8/2/0/7/8/4/RefactoringStartupTools_ch9.mp3" expression="full" duration="896" fileSize="7171341" type="audio/mp3" medium="audio"></media:content>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/8/2/0/7/8/4/RefactoringStartupTools_ch9.mp4" expression="full" duration="896" fileSize="27337695" type="video/mp4" medium="video"></media:content>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/8/2/0/7/8/4/RefactoringStartupTools_ch9.wma" expression="full" duration="896" fileSize="7259631" type="audio/x-ms-wma" medium="audio"></media:content>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/8/2/0/7/8/4/RefactoringStartupTools_ch9.wmv" expression="full" duration="896" fileSize="43586123" type="video/x-ms-wmv" medium="video"></media:content>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/8/2/0/7/8/4/RefactoringStartupTools_Zune_ch9.wmv" expression="full" duration="896" fileSize="27442051" type="video/x-ms-wmv" medium="video"></media:content>
        <media:content url="mms://mschnlnine.wmod.llnwd.net/a1809/d1/ch9/8/2/0/7/8/4/RefactoringStartupTools_s_ch9.wmv" expression="full" duration="896" fileSize="227" type="video/x-ms-wmv" medium="video"></media:content>
      </media:group>      
      <enclosure url="http://ecn.channel9.msdn.com/o9/ch9/8/2/0/7/8/4/RefactoringStartupTools_ch9.wmv" length="43586123" type="video/x-ms-wmv"></enclosure>
      <dc:creator>Howard Dierking</dc:creator>
      <itunes:author>Howard Dierking</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Refactoring/RSS</wfw:commentRss>
      <category>ASP.NET</category>
      <category>Brownfield Development</category>
      <category>MSDN Magazine</category>
      <category>Patterns</category>
      <category>Singleton</category>
    </item>
  <item>
      <title>Extreme ASP.NET Makeover: Disentangling Our Tangled Web-Overview - Overview</title>
      <description><![CDATA[
<p>We’re now on the eighth installment of Extreme ASP.NET Makeover. In part 7, we examined the singleton pattern and refactored away the AuthChecker singleton. AuthorizationServices, which previously used the AuthChecker singleton, now depends on the IAuthorizationChecker
 interface and simply creates an instance of the AuthorizationChecker class in its constructor by calling the new operator. In this intallment, we will discuss better ways to manage dependencies in our applications using an inversion of control container. If
 you are not familiar with inversion of control containers or the related concepts of dependency inversion and dependency injection, take some time to read James’ article on those topics from the March 2008 issue of
<i>MSDN Magazine</i>, <a shape="rect" href="http://msdn.microsoft.com/en-us/magazine/cc337885.aspx" shape="rect">
“Loosen Up: Tame Your Software Dependencies for More Flexible Apps.”</a></p>
<h2>The Tangled Web we Weave</h2>
<p>Let’s take a closer look at AuthorizationServices. AuthorizationServices depends on IAuthorizationChecker, which is implemented by AuthorizationChecker. In turn, AuthorizationChecker depends on Settings to retrieve the configured ISettingsStorageProviderV30,
 which can be a SettingsStorageProvider, SqlSettingsStorageProvider, or other implementation. Now, SettingsStorageProvider depends on IHostV30 and its default implementation by Host. Host is a “God object” in ScrewTurn Wiki. According to Wikipedia, “a
<a shape="rect" href="http://en.wikipedia.org/wiki/God_object" shape="rect">God object</a> is an object that
<i>knows too much</i> or <i>&nbsp;does too much</i>.” A God object is a software anti-pattern.</p>
<p>Host is a coordinator of a wide variety of unrelated activities in ScrewTurn. It handles everything from retrieving settings values to sending emails to handling backups to finding users, Wiki pages, namespaces, categories, and more.
</p>
<p>Many of these responsibilities are delegated to sub-objects, and Host only acts as the coordinator of these services. This is better than having all that functionality actually coded in Host itself. Host does still present a problem in that its delicate
 coordination of all the other objects in the system, especially during application startup, means that it is difficult to refactor the overall system. Moving startup code from one class to another causes breakages as the ordering of construction is slightly
 changed and previously working code throws NullReferenceExceptions as dependencies are unexpectedly null due to construction orderings.</p>
<p>Let’s take a look at Host’s constructor:</p>
<pre>public Host() {    customSpecialTags = new Dictionary&lt;string, CustomToolbarItem&gt;(5);}</pre>
<br>
<p>In its constructor, Host creates a single Dictionary. There is no indication that Host has a dependency problem. Host’s tangled web of dependencies is hidden due to its overuse of Singletons and static helper classes. For example, let’s take a look at a
 few Host methods:</p>
<pre>public UserInfo[] GetUsers() {     return Users.Instance.GetUsers().ToArray();}public PageContent GetPageContent(PageInfo page) {    return Content.GetPageContent(page, true);}public string Format(string raw) {    return Formatter.Format(raw, FormattingContext.Unknown, null);}</pre>
<br>
<p>Note the use of the Users singleton and the static Content an Formatter classes in the above code. Without actually looking at Host’s implementation code, there is no way to tell that it depends on these other classes. To make matters even more complicated,
 Users (and other dependent classes) depend on Host! If constructors aren’t run in the correct order and before certain methods are called, NullReferenceExceptions will be your reward. All of the construction logic is carefully orchestrated by StartupTools,
 which is responsible for constructing and initializing all singletons within the application in the correct order.</p>
<h2>Seeking Salvation</h2>
<p>God objects lead us down a road unto madness. Host’s dependencies are so tangled and interdependent that the result is only somewhat better than a single, monolithic object. So how do we chart a course back to sanity?</p>
<p>Dependencies in software are not fundamentally the problem here. Without dependencies, we wouldn’t be able to write much more than “Hello, World!”-style applications. (Even a simple application like Hello, World! &nbsp;requires dependencies on System.Console
 and System.String, as well as the CLR.) The problem is unchecked and unfettered dependencies between objects that do not need to know about each other. Before we can solve the problem of unnecessary dependencies, we need to make those dependencies obvious.
 How can we construct our classes/objects so that their dependencies are obvious? Make dependencies apparent by declaring them in the classes constructor. For example, let’s look at AuthorizationServices’ constructor:</p>
<pre>public AuthorizationServices(IAuthorizationChecker authorizationChecker) {    this.authorizationChecker = authorizationChecker;}</pre>
<br>
<p>Simply by looking at the constructor’s signature, we can tell that AuthorizationServices requires an IAuthorizationChecker to perform its work. (You probably already knew that because we implemented it in part 7.) The concrete implementation of IAuthorizationChecker
 is AuthorizationChecker:</p>
<pre>public AuthorizationChecker() {    settingsProvider = Settings.Instance.Provider;}</pre>
<br>
<p>Notice that you don’t know that AuthorizationChecker depends on the static Settings class. You have to read AuthorizationChecker’s constructor implementation to figure this out. While not hard, it is not immediately obvious that AuthorizationChecker depends
 on ISettingsStorageProviderV30, which is the type return by the Provider property. How can we make this more obvious? By declaring our intent in the constructor parameters, like so:</p>
<pre>public AuthorizationChecker() : this(Settings.Instance.Provider) {}public AuthorizationChecker(ISettingsStorageProviderV30 settingsProvider) {    if(settingsProvider == null)        throw new ArgumentNullException(&quot;settingsProvider&quot;);    this.settingsProvider = settingsProvider;}</pre>
<br>
<p>Our other code depends on the parameterless constructor. We will leave it in place for now and chain to an overloaded constructor that takes a ISettingsStorageProviderV30. Our dependency on ISettingsStorageProviderV30 has now been made obvious.</p>
<p>We are not out of the proverbial woods yet. Other dependencies are lurking within AuthorizationChecker, namely the static classes AuthTools and AclEvaluator. We can make them obvious dependencies by changing them from static classes to instances and moving
 their initialization to the constructor.</p>
<h2>Other videos from this article</h2>
<ul>
<li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Overview/" shape="rect">Overview</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Refactoring/" shape="rect">Refactoring</a>
</li></ul>
<p>Read the full article at <a shape="rect" href="http://msdn.microsoft.com/magazine/ee424155.aspx" shape="rect">
http://msdn.microsoft.com/magazine/ee424155.aspx</a> </p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Tags/singleton/RSS&WT.dl=0&WT.entryid=Entry:RSSView:41983cd281ff442fbd749deb01770749">]]></description>
      <comments>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Overview</comments>
      <itunes:summary>
We’re now on the eighth installment of Extreme ASP.NET Makeover. In part 7, we examined the singleton pattern and refactored away the AuthChecker singleton. AuthorizationServices, which previously used the AuthChecker singleton, now depends on the IAuthorizationChecker
 interface and simply creates an instance of the AuthorizationChecker class in its constructor by calling the new operator. In this intallment, we will discuss better ways to manage dependencies in our applications using an inversion of control container. If
 you are not familiar with inversion of control containers or the related concepts of dependency inversion and dependency injection, take some time to read James’ article on those topics from the March 2008 issue of
MSDN Magazine, 
“Loosen Up: Tame Your Software Dependencies for More Flexible Apps.” 
The Tangled Web we Weave
Let’s take a closer look at AuthorizationServices. AuthorizationServices depends on IAuthorizationChecker, which is implemented by AuthorizationChecker. In turn, AuthorizationChecker depends on Settings to retrieve the configured ISettingsStorageProviderV30,
 which can be a SettingsStorageProvider, SqlSettingsStorageProvider, or other implementation. Now, SettingsStorageProvider depends on IHostV30 and its default implementation by Host. Host is a “God object” in ScrewTurn Wiki. According to Wikipedia, “a
God object is an object that
knows too much or &amp;nbsp;does too much.” A God object is a software anti-pattern. 
Host is a coordinator of a wide variety of unrelated activities in ScrewTurn. It handles everything from retrieving settings values to sending emails to handling backups to finding users, Wiki pages, namespaces, categories, and more.
 
Many of these responsibilities are delegated to sub-objects, and Host only acts as the coordinator of these services. This is better than having all that functionality actually coded in Host itself. Host does still present a problem in that its delicate
 coordination of </itunes:summary>
      <itunes:duration>585</itunes:duration>
      <link>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Overview</link>
      <pubDate>Tue, 01 Sep 2009 00:10:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Overview</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/100/487027_100x75.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/220/487027_220x165.jpg" height="165" width="220"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_320_ch9.png" height="240" width="320"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_512_ch9.png" height="384" width="512"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_85_ch9.png" height="64" width="85"></media:thumbnail>
      <media:group>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_2MB_ch9.wmv" expression="full" duration="585" fileSize="30333124" type="video/x-ms-wmv" medium="video"></media:content>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_ch9.mp3" expression="full" duration="585" fileSize="4683433" type="audio/mp3" medium="audio"></media:content>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_ch9.mp4" expression="full" duration="585" fileSize="19350270" type="video/mp4" medium="video"></media:content>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_ch9.wma" expression="full" duration="585" fileSize="4745289" type="audio/x-ms-wma" medium="audio"></media:content>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_ch9.wmv" expression="full" duration="585" fileSize="34717775" type="video/x-ms-wmv" medium="video"></media:content>
        <media:content url="http://ecn.channel9.msdn.com/o9/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_Zune_ch9.wmv" expression="full" duration="585" fileSize="19469703" type="video/x-ms-wmv" medium="video"></media:content>
        <media:content url="mms://mschnlnine.wmod.llnwd.net/a1809/d1/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_s_ch9.wmv" expression="full" duration="585" fileSize="263" type="video/x-ms-wmv" medium="video"></media:content>
      </media:group>      
      <enclosure url="http://ecn.channel9.msdn.com/o9/ch9/7/2/0/7/8/4/RefactoringDependenciesIntoTheConstructor_ch9.wmv" length="34717775" type="video/x-ms-wmv"></enclosure>
      <dc:creator>Howard Dierking</dc:creator>
      <itunes:author>Howard Dierking</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Disentangling-Our-Tangled-Web-Overview-Overview/RSS</wfw:commentRss>
      <category>ASP.NET</category>
      <category>Brownfield Development</category>
      <category>MSDN Magazine</category>
      <category>Patterns</category>
      <category>Singleton</category>
    </item>
  <item>
      <title>Extreme ASP.NET Makeover: Singleton - Refactoring</title>
      <description><![CDATA[
<h1>Extreme ASP.NET Makeover: Death of a Singleton-Refactoring</h1>
<p>Now that we have a new class, complete with functionality, we can start to refactor other parts of the application to use it instead of the AuthChecker singleton.&nbsp; Like all the other refactorings we’ve done thus far in this article, it’s not that big of
 a deal.&nbsp; As our example, we’re going to continue to refactor the AuthorizationServices class (see the
<a shape="rect" href="http://msdn.microsoft.com/en-us/magazine/ee210417.aspx" shape="rect">
previous Separation of Concerns article</a> for the initial refactoring for this).&nbsp; In AuthorizationServices, we want to eliminate the use of AuthChecker and, in its place, use an instance of AuthorizationChecker instead.</p>
<p>To do this, we first need to create a module level variable that provides the same capabilities as the AuthChecker singleton.&nbsp; Earlier in this article, we created an IAuthenticationChecker interface that worked to enforce this for us.&nbsp; Now is another time
 that we can use it.&nbsp; As you can see in the code below, we now have created an instance of the AuthenticationChecker and assigned it to the module level variable:</p>
<pre>public class AuthorizationServices{    private IAuthorizationChecker _authenticationChecker;    public AuthorizationServices()    {        authorizationChecker = new AuthorizationChecker();    }    ...}</pre>
<br>
<p>Now that we have a way to access the authentication checking code, we just need to replace the AuthChecker calls in the RetrieveCurrentStatusFor method with calls to the module level variable.&nbsp; As an example of these changes, here is what the first one would
 look like:</p>
<pre>CanView = _authorizationChecker.CheckActionForPage(currentPage,     Actions.ForPages.ReadPage, currentUsername, currentGroups),</pre>
<br>
<p>With that we have our AuthorizationServices class refactored and we’ve finished the first full round of changes that are required to eliminate the AuthChecker singleton.&nbsp; If we take a look at the usages of the AuthChecker singleton instance, we’ll see that
 there are still a large number of places that it is being used.</p>
<p>Now that you’ve finished this first complete refactoring to use the new AuthorizationChecker class, you’ve also reached the first logical checkpoint in your refactoring exercise.&nbsp; From here you can choose when you want to move from the AuthChecker singleton
 to an AuthorizationChecker instance class in any of the other places that AuthChecker is being used.&nbsp; As you incrementally move through your changes from AuthChecker to AuthorizationChecker, you get closer and closer to the next step in this refactoring: deleting
 the AuthChecker singleton.</p>
<p>Once you have all of the usages of AuthChecker replaced with the AuthorizationChecker class you’re almost ready to remove the AuthChecker class from your code base.&nbsp; Before we can do that, remember that we had the new AuthorizationChecker class delegating
 execution to the AuthChecker singleton.&nbsp; To be able to get rid of AuthChecker completely, we need to move its logic into the new AuthorizationChecker class.&nbsp; There are a couple of small things that we need to address in this refactoring, such as adding using
 statements.&nbsp;&nbsp; </p>
<p>The main change we need is to address the code’s need for an ISettingsStorageProviderV30 typed object.&nbsp; If we look into how that object is being passed into the AuthChecker singleton, we see that it’s actually being provided from another singleton named
 Settings:</p>
<pre>AuthChecker.Instance = new AuthChecker(Settings.Instance.Provider);</pre>
<br>
<p>&nbsp;</p>
<p>Since this value is coming from a singleton, we can easily add a module level variable to AuthorizationChecker that can be used throughout its methods.&nbsp; Assigning that variable is as simple as what you see below.&nbsp; Also note that we no longer need the module
 level AuthChecker variable since we’ve now moved all of the AuthChecker code into this class.&nbsp; Since it’s not needed, we’ve removed it and the code related to it in the constructor:</p>
<pre>private ISettingsStorageProviderV30 _settingsProvider; public AuthorizationChecker(){    _settingsProvider = Settings.Instance.Provider;}</pre>
<br>
<p>The result of this final refactoring is that the public methods on AuthChecker are no longer being executed anywhere in the code base.&nbsp; If you were to do a Find Usages on AuthChecker, you’ll see that the only place it exists is in the StartupTools class
 where it was being initialized.&nbsp; Since it’s not being used anywhere, there’s no need to initialize it, so we’ll just delete that line of code.&nbsp; Now we’re completely free of any use of AuthChecker, so we can delete the class from the project.&nbsp; With that, you’re
 free of your singleton past...or at least one part of it.</p>
<h1>I realized what a ridiculous lie my whole life has been...</h1>
<p>We’ve spent some quality time together on this article and have weaned you from a dependence on singletons in your code base.&nbsp; Singletons often are seen as the “easy” way to code.&nbsp; Just because you don’t have to “new up” a class to make use of its functionality,
 doesn’t mean that you’re not imposing a debt on your code base.&nbsp; While singletons seem like the route of least friction at first, you quickly find out that they’re nothing more than a mirage on the way to software development bliss.&nbsp; You see the ease of development
 that they offer, but every time that you move closer the goal is still just as far away as it was before.</p>
<p>Unless you truly need to ensure that one, and only one, instance of an object exists per application lifecycle, then you should be working to refactor singletons out of your code base.&nbsp; Hopefully, the techniques in this article have pointed you in the right
 direction to be able to do that.</p>
<h2>Other videos from this article</h2>
<ul>
<li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Overview/" shape="rect">Demoing Different Singleton Implementations</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Testability/" shape="rect">How Singletons Affect Testability</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-AuthChecker-Class/" shape="rect">Looking At AuthChecker</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Refactoring/" shape="rect">Walkthrough Of The Entire Refactoring</a>
</li></ul>
<p>Read the full article at <a shape="rect" href="http://msdn.microsoft.com/magazine/ee343987.aspx" shape="rect">
http://msdn.microsoft.com/magazine/ee343987.aspx</a> </p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Tags/singleton/RSS&WT.dl=0&WT.entryid=Entry:RSSView:9caf066dd9234821bdd49deb01770b8f">]]></description>
      <comments>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Refactoring</comments>
      <itunes:summary>
Extreme ASP.NET Makeover: Death of a Singleton-Refactoring
Now that we have a new class, complete with functionality, we can start to refactor other parts of the application to use it instead of the AuthChecker singleton.&amp;nbsp; Like all the other refactorings we’ve done thus far in this article, it’s not that big of
 a deal.&amp;nbsp; As our example, we’re going to continue to refactor the AuthorizationServices class (see the

previous Separation of Concerns article for the initial refactoring for this).&amp;nbsp; In AuthorizationServices, we want to eliminate the use of AuthChecker and, in its place, use an instance of AuthorizationChecker instead. 
To do this, we first need to create a module level variable that provides the same capabilities as the AuthChecker singleton.&amp;nbsp; Earlier in this article, we created an IAuthenticationChecker interface that worked to enforce this for us.&amp;nbsp; Now is another time
 that we can use it.&amp;nbsp; As you can see in the code below, we now have created an instance of the AuthenticationChecker and assigned it to the module level variable: 
public class AuthorizationServices{    private IAuthorizationChecker _authenticationChecker;    public AuthorizationServices()    {        authorizationChecker = new AuthorizationChecker();    }    ...}

Now that we have a way to access the authentication checking code, we just need to replace the AuthChecker calls in the RetrieveCurrentStatusFor method with calls to the module level variable.&amp;nbsp; As an example of these changes, here is what the first one would
 look like: 
CanView = _authorizationChecker.CheckActionForPage(currentPage,     Actions.ForPages.ReadPage, currentUsername, currentGroups),

With that we have our AuthorizationServices class refactored and we’ve finished the first full round of changes that are required to eliminate the AuthChecker singleton.&amp;nbsp; If we take a look at the usages of the AuthChecker singleton instance, we’ll see that
 there are sti</itunes:summary>
      <itunes:duration>455</itunes:duration>
      <link>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Refactoring</link>
      <pubDate>Tue, 04 Aug 2009 23:57:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Refactoring</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/100/482733_100x75.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/220/482733_220x165.jpg" height="165" width="220"></media:thumbnail>
      <media:thumbnail url="http://mschnlnine.vo.llnwd.net/d1/ch9/3/3/7/2/8/4/WalkthroughOfTheEntireRefactoring_large_ch9.png" height="240" width="320"></media:thumbnail>
      <media:thumbnail url="http://mschnlnine.vo.llnwd.net/d1/ch9/3/3/7/2/8/4/WalkthroughOfTheEntireRefactoring_small_ch9.png" height="64" width="85"></media:thumbnail>
      <media:group>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/3/3/7/2/8/4/WalkthroughOfTheEntireRefactoring_2MB_ch9.wmv" expression="full" duration="455" fileSize="16059824" type="video/x-ms-wmv" medium="video"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/3/3/7/2/8/4/WalkthroughOfTheEntireRefactoring_ch9.mp3" expression="full" duration="455" fileSize="3643708" type="audio/mp3" medium="audio"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/3/3/7/2/8/4/WalkthroughOfTheEntireRefactoring_ch9.mp4" expression="full" duration="455" fileSize="13461933" type="video/mp4" medium="video"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/3/3/7/2/8/4/WalkthroughOfTheEntireRefactoring_ch9.wma" expression="full" duration="455" fileSize="3687875" type="audio/x-ms-wma" medium="audio"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/3/3/7/2/8/4/WalkthroughOfTheEntireRefactoring_Zune_ch9.wmv" expression="full" duration="455" fileSize="12571877" type="video/x-ms-wmv" medium="video"></media:content>
      </media:group>      
      <enclosure url="http://mschnlnine.vo.llnwd.net/d1/ch9/3/3/7/2/8/4/WalkthroughOfTheEntireRefactoring_2MB_ch9.wmv" length="16059824" type="video/x-ms-wmv"></enclosure>
      <dc:creator>Howard Dierking</dc:creator>
      <itunes:author>Howard Dierking</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Refactoring/RSS</wfw:commentRss>
      <category>ASP.NET</category>
      <category>Brownfield Development</category>
      <category>MSDN Magazine</category>
      <category>Patterns</category>
      <category>Singleton</category>
    </item>
  <item>
      <title>Extreme ASP.NET Makeover: Singleton - AuthChecker Class</title>
      <description><![CDATA[
<h1>Extreme ASP.NET Makeover: Death of a Singleton-AuthChecker Class</h1>
<h1>I’ve Got Some Seeds, Right Away</h1>
<p>So where should we start?&nbsp; How about the AuthChecker class, since that’s what we’ve discussed through the first part of this article.&nbsp; Earlier, we decided that there was no reason for it to continue to be a singleton, since there was no compelling reason
 for one, and only one, instance of it to exist for the life of the application.</p>
<p>The process that we’re going to go through will see us move from using the existing AuthChecker class to using instances of an AuthorizationChecker class.&nbsp; Once we’ve made the transition from AuthChecker to AuthorizationChecker, we will delete the AuthChecker
 Singleton from our codebase.</p>
<p>The first challenge that we have to face in this process is how do we create a new class (AuthorizationChecker) which we can guarantee to expose the same functionality as the original (AuthChecker) class.&nbsp; There are two reasonable options for this: abstract
 base class and interface.&nbsp; Abstract base class is a good solution, if we were going to need to use the same AuthChecker functionality in multiple class implementation for the distant future.&nbsp; In this case though, we’ve already determined that we’re going to
 be deleting the AuthChecker Singleton implementation once we’ve completed our refactoring.&nbsp; As a result, using Interfaces makes more sense.</p>
<p>That makes our first step in the process to extract an interface from the AuthChecker class.&nbsp; As you can see below, it’s really a simple interface, called IAuthorizationChecker, that defines the four publically exposed methods on the AuthChecker class:</p>
<pre>public interface IAuthenticationChecker{    bool CheckActionForGlobals(string action, string currentUser,        string[] groups);    bool CheckActionForNamespace(NamespaceInfo nspace, string action,        string currentUser, string[] groups);    bool CheckActionForPage(PageInfo page, string action,        string currentUser, string[] groups);    bool CheckActionForDirectory(IFilesStorageProviderV30 provider,         string directory, string action, string currentUser, string[] groups);}</pre>
<br>
<p>Now that we have that interface we need to get the AuthChecker to implement it.&nbsp; This is pretty easy, but has a couple of small twists.&nbsp; Because we’re applying the interface to a Singleton class, we also have to ensure that the .Instance property is returning
 a type of the IAuthenticationChecker interface.&nbsp; To get the code to compile we also have to change the type of the properties underlying module level variable so that it too is of type IAuthorizationChecker:</p>
<pre>public class AuthorizationChecker : IAuthorizationChecker{    public bool CheckActionForGlobals(string action,         string currentUser, string[] groups)    {        throw new NotImplementedException();    }     public bool CheckActionForNamespace(NamespaceInfo nspace,         string action, string currentUser, string[] groups)    {        throw new NotImplementedException();    }     public bool CheckActionForPage(PageInfo page, string action,         string currentUser, string[] groups)    {        throw new NotImplementedException();    }     public bool CheckActionForDirectory(        IFilesStorageProviderV30 provider, string directory,         string action, string currentUser, string[] groups)    {        throw new NotImplementedException();    }}</pre>
<br>
<p>Interestingly, this is the last of the changes that you’ll have to make to AuthChecker before you delete it from the project.</p>
<p>Now that we’ve established how calling code should expect us to behave (via the IAuthorizationChecker interface), we can go ahead and write a new class that meets that expectation.&nbsp; In this case we’re going to call the class AuthorizationChecker and we’ll
 make it implement the interface.&nbsp; The result, as shown in <b>Figure 6</b>, is a class with the same four public methods on it that the AuthChecker class has.</p>
<p><b>Figure 6 Class With Four Public Methods</b></p>
<pre>public class AuthorizationChecker : IAuthorizationChecker{    public bool CheckActionForGlobals(string action,         string currentUser, string[] groups)    {        throw new NotImplementedException();    }     public bool CheckActionForNamespace(NamespaceInfo nspace,         string action, string currentUser, string[] groups)    {        throw new NotImplementedException();    }     public bool CheckActionForPage(PageInfo page, string action,         string currentUser, string[] groups)    {        throw new NotImplementedException();    }     public bool CheckActionForDirectory(        IFilesStorageProviderV30 provider,         string directory, string action,         string currentUser, string[] groups)    {        throw new NotImplementedException();    }}</pre>
<br>
<p>Now that our new AuthorizationChecker class has a basic shell, we need to get it working with the same functionality as the original AuthChecker singleton.&nbsp;&nbsp; One of the key things when doing refactorings like this is to be able to do them incrementally.&nbsp;&nbsp;
 Big-bang approaches can be successful, but rarely do you have the ability to impose the constraints, such as time and cost, on your project’s current needs.&nbsp; Instead, we want to be able to nibble away at the refactoring as time permits and in a way that won’t
 affect the project.</p>
<p>To do this, we’re going to take our new AuthenticationChecker class and simply pass through the calls to the original AuthChecker code.&nbsp;&nbsp; This may seem like an extraneous step, but it’s one that is necessary to achieve the goal of refactoring little by little.&nbsp;
 To make this happen, we need to get an instance of AuthChecker into the local scope of the newly created AuthenticationChecker class:</p>
<pre>private IAuthorizationChecker _authChecker; public AuthorizationChecker(){    AuthChecker.Instance = new AuthChecker(Settings.Instance.Provider);    _authChecker = AuthChecker.Instance;}</pre>
<br>
<p>Once we have the AuthChecker instance in place, we can have the methods in the class simply delegate execution to the existing methods in the AuthChecker class.&nbsp; Like we said before, this may seem extraneous, but trust us, we’re going somewhere here, as
 shown in <b>Figure 7</b>.</p>
<p><b>Figure 7 Execution of Existing Methods in the AuthChecker Class</b></p>
<pre>public bool CheckActionForGlobals(string action, string currentUser,     string[] groups){    return _authChecker.CheckActionForGlobals(action, currentUser,        groups);} public bool CheckActionForNamespace(NamespaceInfo nspace,     string action, string currentUser, string[] groups){    return _authChecker.CheckActionForNamespace(nspace, action,         currentUser, groups);} public bool CheckActionForPage(PageInfo page, string action,     string currentUser, string[] groups){    return _authChecker.CheckActionForPage(page, action,         currentUser, groups);} public bool CheckActionForDirectory(IFilesStorageProviderV30 provider,     string directory, string action, string currentUser, string[] groups){    return _authChecker.CheckActionForDirectory(provider, directory,         action, currentUser, groups);}</pre>
<br>
<p>One of the key things to note with this approach is that we’ve maintained a single place of change for the code that is related to the AuthChecker/AuthorizationChecker functionality.&nbsp; If we’re going to be tackling this refactoring over a period of time,
 this is key, since we can’t be confidently maintaining multiple pieces of code that represent the same functionality.&nbsp; Don’t be fooled that the maintenance cost of this approach is zero.&nbsp; If you were to change the arguments in the methods, you’d have multiple
 places to change, but, on a positive note, you’d get compile errors from that due to the use of an interface enforcing the publically exposed contract.</p>
<h2>Other videos from this article</h2>
<ul>
<li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Overview/" shape="rect">Demoing Different Singleton Implementations</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Testability/" shape="rect">How Singletons Affect Testability</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-AuthChecker-Class/" shape="rect">Looking At AuthChecker</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Refactoring/" shape="rect">Walkthrough Of The Entire Refactoring</a>
</li></ul>
<p>Read the full article at <a shape="rect" href="http://msdn.microsoft.com/magazine/ee343987.aspx" shape="rect">
http://msdn.microsoft.com/magazine/ee343987.aspx</a> </p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Tags/singleton/RSS&WT.dl=0&WT.entryid=Entry:RSSView:19aaf3f4aa2445ada17a9deb01770f66">]]></description>
      <comments>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-AuthChecker-Class</comments>
      <itunes:summary>
Extreme ASP.NET Makeover: Death of a Singleton-AuthChecker Class
I’ve Got Some Seeds, Right Away
So where should we start?&amp;nbsp; How about the AuthChecker class, since that’s what we’ve discussed through the first part of this article.&amp;nbsp; Earlier, we decided that there was no reason for it to continue to be a singleton, since there was no compelling reason
 for one, and only one, instance of it to exist for the life of the application. 
The process that we’re going to go through will see us move from using the existing AuthChecker class to using instances of an AuthorizationChecker class.&amp;nbsp; Once we’ve made the transition from AuthChecker to AuthorizationChecker, we will delete the AuthChecker
 Singleton from our codebase. 
The first challenge that we have to face in this process is how do we create a new class (AuthorizationChecker) which we can guarantee to expose the same functionality as the original (AuthChecker) class.&amp;nbsp; There are two reasonable options for this: abstract
 base class and interface.&amp;nbsp; Abstract base class is a good solution, if we were going to need to use the same AuthChecker functionality in multiple class implementation for the distant future.&amp;nbsp; In this case though, we’ve already determined that we’re going to
 be deleting the AuthChecker Singleton implementation once we’ve completed our refactoring.&amp;nbsp; As a result, using Interfaces makes more sense. 
That makes our first step in the process to extract an interface from the AuthChecker class.&amp;nbsp; As you can see below, it’s really a simple interface, called IAuthorizationChecker, that defines the four publically exposed methods on the AuthChecker class: 
public interface IAuthenticationChecker{    bool CheckActionForGlobals(string action, string currentUser,        string[] groups);    bool CheckActionForNamespace(NamespaceInfo nspace, string action,        string currentUser, string[] groups);    bool CheckActionForPage(PageInfo page, string action,  </itunes:summary>
      <itunes:duration>93</itunes:duration>
      <link>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-AuthChecker-Class</link>
      <pubDate>Tue, 04 Aug 2009 23:57:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-AuthChecker-Class</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/100/482732_100x75.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/220/482732_220x165.jpg" height="165" width="220"></media:thumbnail>
      <media:thumbnail url="http://mschnlnine.vo.llnwd.net/d1/ch9/2/3/7/2/8/4/LookingAtAuthChecker_large_ch9.png" height="240" width="320"></media:thumbnail>
      <media:thumbnail url="http://mschnlnine.vo.llnwd.net/d1/ch9/2/3/7/2/8/4/LookingAtAuthChecker_small_ch9.png" height="64" width="85"></media:thumbnail>
      <media:group>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/2/3/7/2/8/4/LookingAtAuthChecker_2MB_ch9.wmv" expression="full" duration="93" fileSize="2742502" type="video/x-ms-wmv" medium="video"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/2/3/7/2/8/4/LookingAtAuthChecker_ch9.mp3" expression="full" duration="93" fileSize="752696" type="audio/mp3" medium="audio"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/2/3/7/2/8/4/LookingAtAuthChecker_ch9.mp4" expression="full" duration="93" fileSize="2705278" type="video/mp4" medium="video"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/2/3/7/2/8/4/LookingAtAuthChecker_ch9.wma" expression="full" duration="93" fileSize="773995" type="audio/x-ms-wma" medium="audio"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/2/3/7/2/8/4/LookingAtAuthChecker_Zune_ch9.wmv" expression="full" duration="93" fileSize="2646809" type="video/x-ms-wmv" medium="video"></media:content>
      </media:group>      
      <enclosure url="http://mschnlnine.vo.llnwd.net/d1/ch9/2/3/7/2/8/4/LookingAtAuthChecker_2MB_ch9.wmv" length="2742502" type="video/x-ms-wmv"></enclosure>
      <dc:creator>Howard Dierking</dc:creator>
      <itunes:author>Howard Dierking</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-AuthChecker-Class/RSS</wfw:commentRss>
      <category>ASP.NET</category>
      <category>Brownfield Development</category>
      <category>MSDN Magazine</category>
      <category>Patterns</category>
      <category>Singleton</category>
    </item>
  <item>
      <title>Extreme ASP.NET Makeover: Singleton - Testability</title>
      <description><![CDATA[
<h1>Extreme ASP.NET Makeover: Death of a Singleton-Testability</h1>
<h1>He’s Liked, But He’s Not Well Liked</h1>
<p>If the current code works, why do we need to get rid of the singleton? What harm is it doing? After all, there’s a reason the pattern has a name. It must be useful.</p>
<p>We have a few issues with singletons. The easiest argument to make is that singletons make your code hard to test. If you make a call to a singleton in a class, then you must make sure the singleton is initialized whenever the test is run. If the singleton
 requires a connection to a database or the existence of a Web service, these must be configured prior to running the test. If you want reasons why this is a bad practice, look no further than our previous article on separation of concerns.</p>
<p>This lack of testability isn’t the only problem. After all, there are ways (usually neither easy nor pleasant) to make singletons testable. Indeed, ScrewTurn uses one of them by exposing a public constructor. Let’s look more closely at the AuthChecker class
 we’ve been working with. Why is it a singleton class? Perhaps so that its members can be accessed throughout the site without having to create a new instance of it? Perhaps to save on resources by reducing object allocation and garbage collection? (This would
 almost certainly be a premature optimization.)</p>
<p>Let’s look at the first public method on the class, CheckActionForGlobals. Where is this being used? If you trace its usages, you’ll find it is used in exactly three other classes: the AdminMaster master page and FileManager.ascx control (both in the WebApplication
 project) and the AuthorizationServices class in the Core project. (The latter is one of the refactorings we did in Part 6; originally, it was being called in Default.aspx in the WebApplication project.)</p>
<p>So this globally accessible method is really only being used in three places. Doesn’t sound all that global to us. One could make an argument that each of these classes could just create an instance of the class instead. That would make them easier to test
 and less fragile overall.</p>
<p>Of course, we’ve been cautiously selective in our example. CheckActionForGlobals is but one method in the AuthChecker singleton. If we look at all cases where we reference AuthChecker.Instance, we’ll find no less than 86 occurrences of it across 21 files.</p>
<p>“Aha!” you say. “Doesn’t that contradict your argument that it’s not really being used globally?” “Pshaw!” say we! What it does is highlight another issue with singletons. The Instance variable is used in 21 files, yet CheckActionForGlobals is used in 3.
 Another method, CheckActionForDirectory, is used in 5, not including calls made from within the AuthChecker class itself.</p>
<p>In short, our singleton has turned into a sort of catch-all bucket, a place to house disparate methods under the loosely-defined category of “authorization checking.” Granted, the AuthChecker class isn’t as messy as it could be, but the tendency with singleton
 classes is to make them more and more generic as you add “helper” methods to them. The ubiquitous Utils singleton often seen in many projects is a good example. Developers see a singleton and it’s just so darned tempting to drop a method in there rather than
 create a separate class with a more specific focus.</p>
<p>The result of those temptations is that you find code bases that are littered with unnecessary singletons.&nbsp; While they may seem innocuous at first, the problems we described earlier will start to haunt your project.&nbsp; To help you with those existing Singletons,
 let’s look at how we can move through our code and remove them.</p>
<h2>Other videos from this article</h2>
<ul>
<li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Overview/" shape="rect">Demoing Different Singleton Implementations</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Testability/" shape="rect">How Singletons Affect Testability</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-AuthChecker-Class/" shape="rect">Looking At AuthChecker</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Refactoring/" shape="rect">Walkthrough Of The Entire Refactoring</a>
</li></ul>
<p>Read the full article at <a shape="rect" href="http://msdn.microsoft.com/magazine/ee343987.aspx" shape="rect">
http://msdn.microsoft.com/magazine/ee343987.aspx</a> </p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Tags/singleton/RSS&WT.dl=0&WT.entryid=Entry:RSSView:87d5d81242724247a4269deb01771341">]]></description>
      <comments>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Testability</comments>
      <itunes:summary>
Extreme ASP.NET Makeover: Death of a Singleton-Testability
He’s Liked, But He’s Not Well Liked
If the current code works, why do we need to get rid of the singleton? What harm is it doing? After all, there’s a reason the pattern has a name. It must be useful. 
We have a few issues with singletons. The easiest argument to make is that singletons make your code hard to test. If you make a call to a singleton in a class, then you must make sure the singleton is initialized whenever the test is run. If the singleton
 requires a connection to a database or the existence of a Web service, these must be configured prior to running the test. If you want reasons why this is a bad practice, look no further than our previous article on separation of concerns. 
This lack of testability isn’t the only problem. After all, there are ways (usually neither easy nor pleasant) to make singletons testable. Indeed, ScrewTurn uses one of them by exposing a public constructor. Let’s look more closely at the AuthChecker class
 we’ve been working with. Why is it a singleton class? Perhaps so that its members can be accessed throughout the site without having to create a new instance of it? Perhaps to save on resources by reducing object allocation and garbage collection? (This would
 almost certainly be a premature optimization.) 
Let’s look at the first public method on the class, CheckActionForGlobals. Where is this being used? If you trace its usages, you’ll find it is used in exactly three other classes: the AdminMaster master page and FileManager.ascx control (both in the WebApplication
 project) and the AuthorizationServices class in the Core project. (The latter is one of the refactorings we did in Part 6; originally, it was being called in Default.aspx in the WebApplication project.) 
So this globally accessible method is really only being used in three places. Doesn’t sound all that global to us. One could make an argument that each of these classes could just create an</itunes:summary>
      <itunes:duration>504</itunes:duration>
      <link>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Testability</link>
      <pubDate>Tue, 04 Aug 2009 23:57:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Testability</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/100/482731_100x75.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/220/482731_220x165.jpg" height="165" width="220"></media:thumbnail>
      <media:thumbnail url="http://mschnlnine.vo.llnwd.net/d1/ch9/1/3/7/2/8/4/HowSingletonsAffectTestability_large_ch9.png" height="240" width="320"></media:thumbnail>
      <media:thumbnail url="http://mschnlnine.vo.llnwd.net/d1/ch9/1/3/7/2/8/4/HowSingletonsAffectTestability_small_ch9.png" height="64" width="85"></media:thumbnail>
      <media:group>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/1/3/7/2/8/4/HowSingletonsAffectTestability_2MB_ch9.wmv" expression="full" duration="504" fileSize="19788520" type="video/x-ms-wmv" medium="video"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/1/3/7/2/8/4/HowSingletonsAffectTestability_ch9.mp3" expression="full" duration="504" fileSize="4039933" type="audio/mp3" medium="audio"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/1/3/7/2/8/4/HowSingletonsAffectTestability_ch9.mp4" expression="full" duration="504" fileSize="15747760" type="video/mp4" medium="video"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/1/3/7/2/8/4/HowSingletonsAffectTestability_ch9.wma" expression="full" duration="504" fileSize="4090417" type="audio/x-ms-wma" medium="audio"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/1/3/7/2/8/4/HowSingletonsAffectTestability_Zune_ch9.wmv" expression="full" duration="504" fileSize="14396569" type="video/x-ms-wmv" medium="video"></media:content>
      </media:group>      
      <enclosure url="http://mschnlnine.vo.llnwd.net/d1/ch9/1/3/7/2/8/4/HowSingletonsAffectTestability_2MB_ch9.wmv" length="19788520" type="video/x-ms-wmv"></enclosure>
      <dc:creator>Howard Dierking</dc:creator>
      <itunes:author>Howard Dierking</itunes:author>
      <slash:comments>1</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Testability/RSS</wfw:commentRss>
      <category>ASP.NET</category>
      <category>Brownfield Development</category>
      <category>MSDN Magazine</category>
      <category>Patterns</category>
      <category>Singleton</category>
    </item>
  <item>
      <title>Extreme ASP.NET Makeover: Singleton - Overview</title>
      <description><![CDATA[
<h1>Extreme ASP.NET Makeover: Death of a Singleton-Overview</h1>
<p>Let’s review one of the changes we made to the code in part 6. In that discussion, we refactored the authorization checking into a separate class, AuthorizationServices. To do that, we moved a lot of code from the Page_Load method of our Default.aspx page
 into it. <b>Figure 1 </b>shows an excerpt from the RetrieveCurrentStatusFor method.</p>
<p><b>Figure 1 Excerpt from the RetrieveCurrentStatusFor Method</b></p>
<pre>return new CurrentCapabilitiesStatus{    CanView = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.ReadPage,        currentUsername, currentGroups),    CanDownloadAttachments = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.DownloadAttachments,        currentUsername, currentGroups),    CanSetPerms = AuthChecker.Instance.CheckActionForGlobals(        Actions.ForGlobals.ManagePermissions,        currentUsername, currentGroups),    CanAdmin = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.ManagePage,        currentUsername, currentGroups),    CanViewDiscussion = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.ReadDiscussion,        currentUsername, currentGroups),    CanPostDiscussion = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.PostDiscussion,        currentUsername, currentGroups),    CanManageDiscussion = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.ManageDiscussion,        currentUsername, currentGroups),    CanEdit = canEdit,    CanEditWithApproval = canEditWithApproval};</pre>
<br>
<p>Notice all the calls to AuthChecker.Instance. This is an example of the Singleton Design Pattern at work. We’ll define it now to get everyone on the same page.</p>
<h1>There Can Be Only One</h1>
<p>The defining characteristic of a singleton class is that there is only one instance of it at any given time (unless it is never used, in which case, there may not be any instances of it depending on how it is implemented).</p>
<p>Implementing a Singleton is not quite as trivial as it sounds. The intuitive approach is to make the constructor private and provide a public static accessor to it, as shown in
<b>Figure 2</b>.</p>
<p><b>Figure 2 Implementing a Singleton </b></p>
<pre>public class MySingleton{    private static MySingleton _instance;     private MySingleton()    {    }     public static MySingleton Instance    {        get        {            if (_instance == null)                _instance = new MySingleton();            return _instance;        }      }     ...}</pre>
<br>
<p>This works fine in single-threaded environments, but not in multi-threaded ones. Two threads could enter the Instance property before the instance variable is instantiated, resulting in two instances of the class. There are a few ways around this,&nbsp; but the
 easiest solution in .NET takes advantage of the CLR and its guarantees around initialization of static variables, as shown in
<b>Figure 3</b>.</p>
<p><b>Figure 3 Dealing With Two Instances of the Class</b></p>
<pre>public class MySingleton{    private static readonly MySingleton _instance = new MySingleton();     private MySingleton()    {    }     public static MySingleton Instance    {        get        {            return _instance;        }      }     ...}</pre>
<br>
<p>The fact that the instance variable is marked static and readonly ensures only one instance can be created, even in multi-threaded environments.&nbsp; Another side effect is that an instance of MySingleton is always going to be created for the _instance variable,
 regardless of if it’s needed or not.&nbsp; This is, however, rarely an issue in real world code.</p>
<h2>Some Background</h2>
<p>A common implementation for singletons is to use double-checked locking, like so:</p>
<pre>if (_instance == null) {</pre>
<pre>&nbsp;&nbsp;&nbsp; lock (_initializationLock) {</pre>
<pre>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if (_instance == null) {</pre>
<pre>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; _instance = new MySingleton();</pre>
<pre>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; </pre>
<pre>&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; </pre>
<pre>}</pre>
<pre>return _instance;</pre>
<p>&nbsp;</p>
<p>On the surface, double-checked locking appears to offer the best of all worlds. Singletons are instantiated lazily, are never instantiated if never used, and do not take an expensive lock after the singleton is initialized. Unfortunately, double-checked
 locking is subtlely broken in the vast majority of cases. You can read more about the problems in
<a shape="rect" href="http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html" shape="rect">
<i>The “Double-Checked Locking is Broken” Declaration</i></a> by David Bacon, et al. Double-checked locking can be fixed on the CLR (and JDK5&#43;) by declaring the _instance variable with the volatile keyword. See
<a shape="rect" href="http://msdn.microsoft.com/en-us/library/ms998558.aspx" shape="rect">
<i>Implementing Singleton in C#</i></a> and <a shape="rect" href="http://msdn.microsoft.com/en-us/library/ms954629.aspx" shape="rect">
<i>Exploring the Singleton Design Pattern</i></a> in the MSDN Library<i> </i>for more information.</p>
<p>That’s about as detailed as we’re going to get on implementing singletons, because there are a number of good resources already available. Plus, the focus of this article is to move away from them, not add more.</p>
<p>With that background behind us, the “singleton” classes in ScrewTurn aren’t actually singletons.
<b>Figure 4</b> looks at the AuthChecker class first.</p>
<p><b>Figure 4 AuthChecker Class</b></p>
<pre>public class AuthChecker {     private static AuthChecker instance;    public static AuthChecker Instance     {        get { return instance; }        set { instance = value; }    }     private ISettingsStorageProviderV30 settingsProvider;     public AuthChecker(ISettingsStorageProviderV30 settingsProvider)     {        if(settingsProvider == null) throw new             ArgumentNullException(&quot;settingsProvider&quot;);         this.settingsProvider = settingsProvider;    }     public bool CheckActionForGlobals(string action,         string currentUser, string[] groups)     {       }     public bool CheckActionForNamespace(NamespaceInfo nspace,         string action, string currentUser,         string[] groups)     {       }     public bool CheckActionForPage(PageInfo page, string action,     {       }     public bool CheckActionForDirectory(        IFilesStorageProviderV30 provider,         string directory, string action,         string currentUser, string[] groups)     {       }}</pre>
<br>
<p>The most obvious way you can tell this isn’t a singleton is that it has a public constructor. So the client code can create as many of these as it likes. Furthermore, the class doesn’t actually instantiate the instance variable itself. That is done elsewhere
 in the code, in StartupTools.cs, using the public constructor.</p>
<p>That said, it is still used as a singleton within the context of the application. Yes, the code could create more than one instance and re-assign the existing instance and basically treat it like any other class. But in the application’s current state, it
 doesn’t. This half-way status between singleton and non-singleton would be a bone of contention for us at a code review, so let’s see what we can do to fix it. But first, like any refactoring, we need to justify it.</p>
<h2>Other videos from this article</h2>
<ul>
<li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Overview/" shape="rect">Demoing Different Singleton Implementations</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Testability/" shape="rect">How Singletons Affect Testability</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-AuthChecker-Class/" shape="rect">Looking At AuthChecker</a>
</li><li><a shape="rect" href="http://channel9.msdn.com/posts/howarddierking/Extreme-ASPNET-Makeover-Singleton-Refactoring/" shape="rect">Walkthrough Of The Entire Refactoring</a>
</li></ul>
<p>Read the full article at <a shape="rect" href="http://msdn.microsoft.com/magazine/ee343987.aspx" shape="rect">
http://msdn.microsoft.com/magazine/ee343987.aspx</a> </p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Tags/singleton/RSS&WT.dl=0&WT.entryid=Entry:RSSView:e9d5d506bb494bfa92669deb01771702">]]></description>
      <comments>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Overview</comments>
      <itunes:summary>
Extreme ASP.NET Makeover: Death of a Singleton-Overview
Let’s review one of the changes we made to the code in part 6. In that discussion, we refactored the authorization checking into a separate class, AuthorizationServices. To do that, we moved a lot of code from the Page_Load method of our Default.aspx page
 into it. Figure 1 shows an excerpt from the RetrieveCurrentStatusFor method. 
Figure 1 Excerpt from the RetrieveCurrentStatusFor Method 
return new CurrentCapabilitiesStatus{    CanView = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.ReadPage,        currentUsername, currentGroups),    CanDownloadAttachments = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.DownloadAttachments,        currentUsername, currentGroups),    CanSetPerms = AuthChecker.Instance.CheckActionForGlobals(        Actions.ForGlobals.ManagePermissions,        currentUsername, currentGroups),    CanAdmin = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.ManagePage,        currentUsername, currentGroups),    CanViewDiscussion = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.ReadDiscussion,        currentUsername, currentGroups),    CanPostDiscussion = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.PostDiscussion,        currentUsername, currentGroups),    CanManageDiscussion = AuthChecker.Instance.CheckActionForPage(        currentPage, Actions.ForPages.ManageDiscussion,        currentUsername, currentGroups),    CanEdit = canEdit,    CanEditWithApproval = canEditWithApproval};

Notice all the calls to AuthChecker.Instance. This is an example of the Singleton Design Pattern at work. We’ll define it now to get everyone on the same page. 
There Can Be Only One
The defining characteristic of a singleton class is that there is only one instance of it at any given time (unless it is never used, in which case, t</itunes:summary>
      <itunes:duration>511</itunes:duration>
      <link>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Overview</link>
      <pubDate>Tue, 04 Aug 2009 23:56:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Overview</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/100/482728_100x75.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/previewImages/220/482728_220x165.jpg" height="165" width="220"></media:thumbnail>
      <media:thumbnail url="http://mschnlnine.vo.llnwd.net/d1/ch9/8/2/7/2/8/4/DemoingDifferentSingletonImpls_large_ch9.png" height="240" width="320"></media:thumbnail>
      <media:thumbnail url="http://mschnlnine.vo.llnwd.net/d1/ch9/8/2/7/2/8/4/DemoingDifferentSingletonImpls_small_ch9.png" height="64" width="85"></media:thumbnail>
      <media:group>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/8/2/7/2/8/4/DemoingDifferentSingletonImpls_2MB_ch9.wmv" expression="full" duration="511" fileSize="9579476" type="video/x-ms-wmv" medium="video"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/8/2/7/2/8/4/DemoingDifferentSingletonImpls_ch9.mp3" expression="full" duration="511" fileSize="4089664" type="audio/mp3" medium="audio"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/8/2/7/2/8/4/DemoingDifferentSingletonImpls_ch9.mp4" expression="full" duration="511" fileSize="13314207" type="video/mp4" medium="video"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/8/2/7/2/8/4/DemoingDifferentSingletonImpls_ch9.wma" expression="full" duration="511" fileSize="4138475" type="audio/x-ms-wma" medium="audio"></media:content>
        <media:content url="http://mschnlnine.vo.llnwd.net/d1/ch9/8/2/7/2/8/4/DemoingDifferentSingletonImpls_Zune_ch9.wmv" expression="full" duration="511" fileSize="12508647" type="video/x-ms-wmv" medium="video"></media:content>
      </media:group>      
      <enclosure url="http://mschnlnine.vo.llnwd.net/d1/ch9/8/2/7/2/8/4/DemoingDifferentSingletonImpls_2MB_ch9.wmv" length="9579476" type="video/x-ms-wmv"></enclosure>
      <dc:creator>Howard Dierking</dc:creator>
      <itunes:author>Howard Dierking</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/Blogs/howarddierking/Extreme-ASPNET-Makeover-Singleton-Overview/RSS</wfw:commentRss>
      <category>ASP.NET</category>
      <category>Brownfield Development</category>
      <category>MSDN Magazine</category>
      <category>Patterns</category>
      <category>Singleton</category>
    </item>    
</channel>
</rss>