When developing applications in .NET Core, you might often need a single, shared instance of a class. Typical use cases would be an instance of LogManager, StateManager, etc. You can either use a singleton class or a static class to achieve this. The decision on which to choose—singleton or static—depends on several factors. This article explains singleton classes and static classes and when we should we use one versus the other.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. You can download .NET 5.0 from here.

Create an ASP.NET Core 5 MVC project in Visual Studio 2019

First off, let’s create an ASP.NET Core project in Visual Studio 2019. Following these steps should create a new ASP.NET 5 project in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, select .NET 5.0 as the target framework from the drop-down list at the top.
  9. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we won’t be using any of those features here.
  10. Ensure that Authentication is set to “None” as we won’t be using authentication either.
  11. Click Create.

Singleton class or static class? How to choose

We’ll compare and contrast a singleton class and a static class based on the following points:

  • Dependency injection
  • Memory management
  • Extensibility
  • Testability

In the sections that follow, we’ll implement two classes — a static class named StaticLogger and a singleton class named SingletonLogger. Both of these classes provide a Log method that can be used to log data to a specific log target. In both examples below I have omitted the necessary code for logging the data for brevity. (You can read more about static classes and static class members in C# in my previous article here.)

Create a static logger class in C#

Static classes cannot be instantiated or extended. They are abstract and sealed implicitly. To declare a class as static, you should mark it with the static keyword in the class declaration. The static keyword allows you to define both static classes and static members.

Copyright © 2021 IDG Communications, Inc.