Design Patterns

Back to Basics : Singleton Design Pattern using System.Lazy type

June 25, 2015 .NET, .NET Framework, .NET Framework 4.5, .NET Framework 4.5.2, .NET Framework 4.6, Back-2-Bascis, BCL(Base Class Library), C#.NET, Codes, Design Patterns, KnowledgeBase, Microsoft, Portable Class Library, Visual Studio 2013, Visual Studio 2015, VisualStudio, VS2010, VS2012, VS2013, VS2015, Windows No comments

This article takes you to a simpler/alternative approach in making a Singleton Design Pattern implementation using System.Lazy class rather that using our traditional approach.

Singleton Design Pattern implementation without lazy initialization:

  • This code is thread safe enabled

<br />
 /// &lt;summary&gt;<br />
    /// Singleton class<br />
    /// &lt;/summary&gt;<br />
    public class AppConfig<br />
    {</p>
<p>        private AppConfig()<br />
        {</p>
<p>        }</p>
<p>        /// &lt;summary&gt;<br />
        /// Gets the current date time.<br />
        /// &lt;/summary&gt;<br />
        /// &lt;value&gt;<br />
        /// The current date time.<br />
        /// &lt;/value&gt;<br />
        public DateTime CurrentDateTime<br />
        {<br />
            get<br />
            {<br />
                return DateTime.Now;<br />
            }<br />
        }<br />
        /// &lt;summary&gt;<br />
        /// The _config<br />
        /// &lt;/summary&gt;<br />
        private static AppConfig _config;</p>
<p>        /// &lt;summary&gt;<br />
        /// The pad lock for maintaining a thread lock.<br />
        /// &lt;/summary&gt;<br />
        private static readonly Object padLock = new object();</p>
<p>        /// &lt;summary&gt;<br />
        /// Gets the instance.<br />
        /// &lt;/summary&gt;<br />
        /// &lt;value&gt;<br />
        /// The instance.<br />
        /// &lt;/value&gt;<br />
        public static AppConfig Instance<br />
        {<br />
            get<br />
            {</p>
<p>                if (_config == null)<br />
                {<br />
                    lock (padLock) // making thread-safe<br />
                    {<br />
                        //{<br />
                        if (_config == null) //second level check to make sure, within the short span, another concurent thread didnt initialize the object.<br />
                        {<br />
                            _config = new AppConfig();<br />
                        }<br />
                    }<br />
                }<br />
                //}</p>
<p>                return _config;<br />
            }<br />
        }<br />
    }<br />

This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a padLock instance to lock on, rather than locking on the type itself, to avoid deadlocks.

Another variant using Lazy initialization using static constructor and thread safe since initialization is handled during runtime within readonly variable declaration.  This will be thread-safe any ways.

<br />
 /// &lt;summary&gt;<br />
    /// a Simpler version of Singleton class with lazy initialization.<br />
    /// &lt;/summary&gt;<br />
    public class AppConfigLazy1<br />
    {<br />
        // static holder for instance, will not get initialized until first use, due to static contructor.<br />
        private static readonly AppConfigLazy1 _instance = new AppConfigLazy1();</p>
<p>        /// &lt;summary&gt;<br />
        /// Prevents a default instance of the &lt;see cref=&amp;quot;AppConfigLazy1&amp;quot;/&gt; class from being created.<br />
        /// &lt;/summary&gt;<br />
        private AppConfigLazy1()<br />
        {</p>
<p>        }</p>
<p>        /// &lt;summary&gt;<br />
        /// for Lazy Initializes the &lt;see cref=&amp;quot;AppConfigLazy1&amp;quot;/&gt; class.<br />
        /// &lt;/summary&gt;<br />
        static AppConfigLazy1()<br />
        {</p>
<p>        }</p>
<p>        public static AppConfigLazy1 Instance<br />
        {<br />
            get<br />
            {<br />
                return _instance;<br />
            }<br />
        }<br />
    }<br />

Now with .NET 4.0 onwards there is a better way of doing this using .NET Runtime methods using System.Lazy type. System.Lazy type is mainly used in Entity Framework context, but we can use the same in implementing lazy loading where ever we have to deal with memory intensive object or collection of objects.

System.Lazy type  guarantees thread-safe lazy-construction. (By default, all public and protected members of the Lazy class are thread safe and may be used concurrently from multiple threads.)

.NET Framework Support in: 4.6, 4.5, 4

<br />
/// &lt;summary&gt;<br />
    /// a Simpler version of Singleton class with lazy initialization.<br />
    /// &lt;/summary&gt;<br />
    public class AppConfigLazy2<br />
    {<br />
        // static holder for instance, need to use lambda to construct since constructor private<br />
        private static readonly Lazy&lt;AppConfigLazy2&gt; _instance = new Lazy&lt;AppConfigLazy2&gt;(() =&gt; new AppConfigLazy2());</p>
<p>        /// &lt;summary&gt;<br />
        /// Prevents a default instance of the &lt;see cref=&amp;quot;AppConfigLazy2&amp;quot;/&gt; class from being created.<br />
        /// &lt;/summary&gt;<br />
        private AppConfigLazy2()<br />
        {</p>
<p>        }</p>
<p>        public static AppConfigLazy2 Instance<br />
        {<br />
            get<br />
            {<br />
                return _instance.Value;<br />
            }<br />
        }</p>
<p>        /// &lt;summary&gt;<br />
        /// Gets the current date time.<br />
        /// &lt;/summary&gt;<br />
        /// &lt;value&gt;<br />
        /// The current date time.<br />
        /// &lt;/value&gt;<br />
        public DateTime CurrentDateTime<br />
        {<br />
            get<br />
            {<br />
                return DateTime.Now;<br />
            }<br />
        }<br />
    }</p>
<p>

That’s more than one way doing Singleton Pattern Implementation right?, hope that was helpful to you  Some reference links are given below:

Static vs Singleton Classes

May 20, 2015 .NET, .NET Framework, C#.NET, Design Patterns, Interview Qns, KnowledgeBase, Microsoft No comments

Recently while I was attending an interview I came across a question Static vs Singleton. Though I know the differences I couldn’t answer it properly, as I was not refreshed my programming knowledge before the interview.

I would like to quote a reference to Jalpesh’s blog article (www.dotnetjalps.com) explaining the difference:

Difference between Static and Singleton classes:

  1. A singleton classes allowed to create a only single instance or particular class. That instance can be treated as normal object. You can pass that object to a method as parameter or you can call the class method with that Singleton object. While static class can have only static methods and you can not pass static class as parameter.
  2. We can implement the interfaces with the Singleton class while we can not implement the interfaces with static classes.
  3. We can clone the object of Singleton classes we can not clone the object of static classes.
  4. Singleton objects stored on heap while static class stored in stack.
  5. A Singleton class can extend the classes(support inheritance) while static class can not inherit classes.
  6. Singleton class can initialize lazy way while static class initialize when it loaded first
  7. Static classes are sealed class while Single ton classes are not sealed.

Credits to Jalpesh Vadgama  – “Computer Geek, Developer, Mentor, Life long learner, 10+ Years of Experience in Microsoft.NET Technologies, Awarded Microsoft Mvp(C#) for year 2010,11 and 2012.”

Enterprise Solution Patterns Using Microsoft .NET – Version 2.0

January 9, 2012 .NET, .NET Framework, All, Architectures, ASP.NET, Books I Like, Design Patterns, Enterprise Library, KnowledgeBase, Microsoft, Patterns&Practices, Recommends No comments

This is a little old document. But very useful for people who would like to learn more about “Enterprise Solution Patterns using Microsoft.NET” , by Microsoft Patterns & Practices

This document is very good for referencing for common solution patterns and provides little more focus on ASP.NET based Solution Pattterns.

Nice reference though!!.

Enterprise Library 5.0 & Unity 2.1(Dependency Injection Container) for Silverlight and Enterprise Library 5.0 Optional Update 1 for .NET(ASP.NET,WinForms)

May 15, 2011 .NET, .NET Framework, All, ASP.NET, ASP.NET MVC, C#.NET, Design Patterns, Frameworks, General, IIS, IIS 7.5, Microsoft, Patterns&Practices, VB.NET, VisualStudio, VS2010 No comments

Microsoft has recently released few updates for Microsoft Enterprise Library 5.0 (A collection of reusable application blocks(logging,caching, cryptography, data access etc) for .NET.

One of the interesting part of these releases are Enterprise Library 5.0 & Unity 2.1(Dependency Injection Container) for Silverlight. more details about each release are given below.

Enterprise Library 5.0 for Silverlight

This release provides many of the features of Enterprise Library 5.0 for Silverlight application developers.
Unity 2.1 for Silverlight

Unity is a dependency injection container. It is full-featured, with support for instance and type interception and custom extensions. This release is a port of Unity 2.1 to Microsoft Silverlight 3, 4 and 5 beta.

Enterprise Library 5.0 Optional Update 1

This package contains Enterprise Library 5.0 with fixes for Unity Interception and file configuration source. This update is required if you are using the Silverlight Integration Pack and need WCF RIA Services Integration or configuration tool support.
Unity 2.1 (latest update for Unity – Microsoft’s Dependency Injection Container)

Unity is a dependency injection container. It is full-featured, with support for instance and type interception and custom extensions.

These new updates will help Silverlight Application developers to leverage the capabilities of Microsoft Enterprise Library 5.0.
Nice work Microsoft.