C# Singleton basics
Introduction The Singleton pattern ensures that a class has only one instance throughout an application and provides a single, globally accessible way to retrieve it. Learn through examples of common use cases with several code samples. All code was written in Microsoft Visual Studio 2026. Advantages : A Singleton provides controlled access to a shared resource, avoids the overhead and…
The Singleton pattern restricts a class to a single instance across an application, offering a single, globally accessible way to obtain it. This is illustrated through various code samples written in Microsoft Visual Studio 2026. The benefits include controlled access to shared resources, avoidance of multiple instance creation overhead, centralized services like configuration, logging, or caching, and support for lazy initialization, creating the instance only upon first request.
To implement a Singleton, two essential rules must be followed: the class should be marked as sealed to prevent subclassing, and a private parameterless constructor to prohibit external creation of new instances using the 'new' keyword.
In the source code library, an example demonstrates a class for listing month names and indices, useful in a web project dropdown element for add and edit pages. Utilizing the 'Lazy' class ensures thread safety and lazy initialization without explicit code. A static property 'Instance' retrieves the singleton instance.
An ASP.NET Core example shows how to create a dropdown using 'Helpers.Instance.MonthList'. The 'OnGet' method populates the dropdown with month items, while the 'OnPost' method handles form submission to update the selected month. The 'OnGet' method retrieves the month list from the singleton instance, and 'OnPost' updates the 'SelectedMonthItem' property if a month is selected.
The Dependency Injection version introduces an alternative approach, leveraging the .NET Core framework's built-in dependency injection mechanism to manage the singleton instance. This approach simplifies the Singleton implementation and integrates seamlessly with the broader application architecture.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.