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
 /// <summary>
    /// Singleton class 
    /// </summary>
    public class AppConfig
    {

        private AppConfig()
        {

        }

        /// <summary>
        /// Gets the current date time.
        /// </summary>
        /// <value>
        /// The current date time.
        /// </value>
        public DateTime CurrentDateTime
        {
            get
            {
                return DateTime.Now;
            }
        }
        /// <summary>
        /// The _config
        /// </summary>
        private static AppConfig _config;

        /// <summary>
        /// The pad lock for maintaining a thread lock.
        /// </summary>
        private static readonly Object padLock = new object();

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>
        /// The instance.
        /// </value>
        public static AppConfig Instance
        {
            get
            {

                if (_config == null)
                {
                    lock (padLock) // making thread-safe
                    {
                        //{
                        if (_config == null) //second level check to make sure, within the short span, another concurent thread didnt initialize the object. 
                        {
                            _config = new AppConfig();
                        }
                    }
                }
                //}

                return _config;
            }
        }
    }

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.

 /// <summary>
    /// a Simpler version of Singleton class with lazy initialization.
    /// </summary>
    public class AppConfigLazy1
    {
        // static holder for instance, will not get initialized until first use, due to static contructor.
        private static readonly AppConfigLazy1 _instance = new AppConfigLazy1();

        /// <summary>
        /// Prevents a default instance of the <see cref=&quot;AppConfigLazy1&quot;/> class from being created.
        /// </summary>
        private AppConfigLazy1()
        {

        }

        /// <summary>
        /// for Lazy Initializes the <see cref=&quot;AppConfigLazy1&quot;/> class.
        /// </summary>
        static AppConfigLazy1()
        {

        }


        public static AppConfigLazy1 Instance
        {
            get
            {
                return _instance;
            }
        }
    }

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
/// <summary>
    /// a Simpler version of Singleton class with lazy initialization.
    /// </summary>
    public class AppConfigLazy2
    {
        // static holder for instance, need to use lambda to construct since constructor private
        private static readonly Lazy<AppConfigLazy2> _instance = new Lazy<AppConfigLazy2>(() => new AppConfigLazy2());

        /// <summary>
        /// Prevents a default instance of the <see cref=&quot;AppConfigLazy2&quot;/> class from being created.
        /// </summary>
        private AppConfigLazy2()
        {

        }
        
        public static AppConfigLazy2 Instance
        {
            get
            {
                return _instance.Value;
            }
        }


        /// <summary>
        /// Gets the current date time.
        /// </summary>
        /// <value>
        /// The current date time.
        /// </value>
        public DateTime CurrentDateTime
        {
            get
            {
                return DateTime.Now;
            }
        }
    }
    

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.