Singleton Design Pattern Real Time Example in C#

Singleton Design Pattern Real Time Example in C# – Exception Logging

In this article, I am going to discuss the Singleton Design Pattern Real Time Example in C#. As part of this article, we will discuss how to create a custom logger library using the Singleton Design Pattern which will log the exceptions to an external file using an ASP.NET MVC application.

We are going to use the following Employee table in this demo.

Singleton Design Pattern Real Time Example in C#

Please use below SQL script to create and populate the Employee table with the required test data.

-- Create a database Called EmployeeDB
CREATE DATABASE EmployeeDB
GO

USE EmployeeDB
GO

-- Create a table called Employee
CREATE TABLE Employee (
    [Id]             INT      IDENTITY (1, 1) NOT NULL,
    [Name]           VARCHAR (50) NOT NULL,
    [Gender]		 VARCHAR (50) NOT NULL,
    [Salary]         BIGINT NOT NULL,
    [Department]     VARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO

-- Insert some test data to the Employee table
INSERT INTO Employee VALUES('Pranaya', 'Male', 12345, 'IT') 
INSERT INTO Employee VALUES('Anurag', 'Male', 100000, 'Sales') 
INSERT INTO Employee VALUES('Priyanka', 'Female', 20000, 'IT') 
INSERT INTO Employee VALUES('Preety', 'Female', 30000, 'HR') 
INSERT INTO Employee VALUES('James', 'Male', 250000, 'HR') 
INSERT INTO Employee VALUES('Pam', 'Feale', 30000, 'IT') 
INSERT INTO Employee VALUES('Smith', 'Male', 220000, 'Sales') 
GO

-- Fetch the data from the Employee table
SELECT * FROM Employee
GO
Create a new MVC application

Open the Visual Studio and then select File => New => Project as shown in the below image

Singleton Design Pattern Real Time Example in C#

Once you click on the Project link a new window will open for selecting the New Project. Now from the New Project window Select the Web option which is inside the Visual C# which is under the Installed section and From the middle pane select the ASP.NET Web Application and name the project as SingletoninMVC and then click on the OK button as shown in the below image

Singleton Design Pattern Real Time Example in C#

Once you click on the OK button, a new window will open with Name New ASP.NET Web Application for selecting project Templates. From this window select the MVC project template and then we are going to choose the Authentication type and for doing that just click on Change Authentication button, a new dialog will pop up with the name Change Authentication here we are going to choose No Authentication and then click on the OK button as shown in the below image.

Singleton Design Pattern Real Time Example in C#

Once you click on the OK button, It will take some to time create the project for us.

Adding ADO.NET Entity Data Model

Next, add ADO.NET Entity Data Model inside Models Folder. To do so, right-click on Models folder then select Add => New Item which will open the Entity Data Model Wizard. From this wizard, from the left pane select Data which is inside Visual C# which is under the Installed section and from the middle pane select ADO.NET Entity Data Model, Provide a meaningful name as “EmployeeDataModel” and then click on ADD button as shown in the below image.

Singleton Design Pattern Real Time Example in C#

Once you click on the Add button, it will open a new window for selecting the Model type. From this window choose Generate From Database option and then click on the Next button as shown below

Singleton Design Pattern Real Time Example in C#

Once you click on the Next button, it will open the Choose Your Data Connection Wizard. From that wizard click on the New Connection button which will open the Connection Properties window. From this connection properties window provide the necessary details, select the database and then click on the OK button as shown below

Singleton Design Pattern Real Time Example in C#

Once you click on the OK button, it will take you back to the Choose Your Data Connection Wizard. Here in this window, you need to provide a meaningful name such as “EmployeeDBContext” for the Context class and that name will be the Connection String name that is going to create in Web.config file and then click on the Next as shown below

Singleton Design Pattern Real Time Example in C#

Once you click on the Next button, it will open the Choose Your Version wizard for selecting the Entity Framework version. From this window, select the Entity Framework 6.x and click on Next button as shown below

Singleton Design Pattern Real Time Example in C#

Once you select the Entity Framework Version and click on the Next button, it will open the Choose Your Database Objects and settings wizard. From this wizard, select the Employee object, provide a meaningful namespace name and finally click on the Finish button as shown in the image below.

Singleton Design Pattern Real Time Example in C#

Next, add a folder with the name as Logger and create the following classes within the Logger folder.

ILog.cs
namespace SingletoninMVC.Logger
{
    public interface ILog
    {
        void LogException(string message);
    }
}

Log.cs

namespace SingletoninMVC.Logger
{
    public sealed class Log: ILog
    {
        private Log()
        {
        }
        private static readonly Lazy<Log> instance = new Lazy<Log>(() => new Log());

        public static Log GetInstance
        {
            get
            {
                return instance.Value;
            }
        }

        public void LogException(string message)
        {
            string fileName = string.Format("{0}_{1}.log", "Exception", DateTime.Now.ToShortDateString());
            string logFilePath = string.Format(@"{0}\{1}", AppDomain.CurrentDomain.BaseDirectory, fileName);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("----------------------------------------");
            sb.AppendLine(DateTime.Now.ToString());
            sb.AppendLine(message);
            using (StreamWriter writer = new StreamWriter(logFilePath, true))
            {
                writer.Write(sb.ToString());
                writer.Flush();
            }
        }
    }
}
Adding Employee Controller:

Add an Employee controller. Here you need to choose the MVC 5 Controller with views using Entity Framework and then you need to use the model “Employee” which will create the views for Employee model which facilitate the CRUD Operations on the employee model as shown below.

Singleton Design Pattern Real Time Example in C#

Once you click on the Add button, it will open the below window. From this window provide the necessary details as the Model class, Data context class, and Controller name and click on the Add button which will create the controller.

Singleton Design Pattern Real Time Example in C#

EmployeeController.cs

Modify the Employee Controller as shown below.

That’s it. We have done with our implementation.

Testing the Application.

Now run the application and you will see that all the exceptions are going to be logged under the file created by the logger class. You can find the Exception Log file as shown in the below path.

Singleton Design Pattern Real Time Example in C#

This Proves that singleton design pattern comes in handy in the situations where we need to have a single instance of the object. In the next article, I will discuss how to implement Caching using the Singleton Design Pattern in an MVC application.

SUMMARY

In this article, I try to explain  Singleton Design Pattern Real Time Example in C# step by step with a real-time example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

2 thoughts on “Singleton Design Pattern Real Time Example in C#”

  1. Aymeric Challier

    Thanx for this articles. They are very interesting. It’s very well explained.

    I just have some difficulties, if I do my connection using the easiest way. Why will it be less good? More exactly, what are the advantages of this method?

    I still have difficulties to understand, why to use singleton?

  2. Hi , As you mentioned ,
    In the next article, I will discuss how to implement Caching using the Singleton Design Pattern in an MVC application.

    can you please share the link

    Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *