C# Singleton - Basic Implementation and strategy - c#

New C# devloper and programmer in general. I am hoping to gain insight into the overall proper usage of a Singleton, with insight on properly accessing class items. I cannot seem to figure out how this is done properly.
Background:
I am developing a C# WPF Application, employing MVVM.
The goal of my Singleton is to provide a globally-accessible class, where I am able to update the values inside within my Model.
This Singleton is called out at the top of my ViewModel, using the following syntax:
public CurrentMDL_Singleton currentMDL_Singleton = CurrentMDL_Singleton.Instance;
One of my ViewModels contains the following class:
public class CurrentMDL_Singleton
{
private static CurrentMDL_Singleton instance;
private CurrentMDL_Singleton()
{
CurrentMDL_Constructor currentMDL_Constructor = new CurrentMDL_Constructor();
}
public static CurrentMDL_Singleton Instance
{
get
{
if(instance == null)
{
//Create a new instance
instance = new CurrentMDL_Singleton();
}
return instance;
}
}
}
Knowledge Check:
I intend to use this Singleton to create an instance of "currentMDL_Constructor". currentMDL_Constructor is another class which exists within the same ViewModel, seen below:
public class CurrentMDL_Constructor
{
public Microsoft.Office.Interop.Excel.Application CurrentMDL_Excel { get; set; }
public Microsoft.Office.Interop.Excel.Workbook CurrentMDL_Workbook { get; set; }
public Microsoft.Office.Interop.Excel.Worksheet CurrentMDL_Worksheet { get; set; }
public Microsoft.Office.Interop.Excel.Range CurrentMDL_xlRange { get; set; }
}
Problems:
I am unable to access the currentMDL_Constructor instance, created by the Singleton, as the Singleton constructor is a private member (understandable given the Singleton's purpose).
Within my Model, I am trying to tap into currentMDL_Constructor, to conduct something like the following:
CurrentMDL_Excel = new Microsoft.Office.Interop.Excel.Application();
CurrentMDL_Workbook = CurrentMDL_Excel.Workbooks.Open(MainWindow.MDL_Compare_VM.CurrentMDL_File);
I am unable to access currentMDL_Constructor to begin even thinking about having access to my CurrentMDL_Constructor class.
What is it that I am not understanding? I feel like I am getting lost in the world of instantiation, nested classes and a lack of basic knowledge with Singleton usage, and object orientation in general.
Thank you in advance, and I apologize if this post is redundant (could not find one that helped me).
-Chris

Your code has multiple issues:
First, when writing a singleton that has no dependencies to other classes like in your case, it is best practise to have a static readonly field that holds the single instance, but you should instantiate it straight away like so:
private static CurrentMDL_Singleton instance = new CurrentMDL_Singleton();
This is because, whenever you reference a singleton class, you will probably use its instance. Moving the instantiation to a field init moves it into the type loader and therefore makes it thread-safe. In your code, if clients access the Instance property in parallel, you may end up in a race condition and hence with two different instances of a singleton class, which is something that you would typically want to avoid.
Second, your constructor creates an object and does not save it anywhere, hence you can't access it.
Third, there is absolutely no need to have an instance variable holding a singleton instance, because you can always get it from the static instance field. In your case, it is even dangerous because someone could change it to null and you would not notice.
Lastly, you should really reconsider whether it is really a singleton that you need. A singleton pattern is applied to make sure that there is only one instance of a class, usually not because it is easier to query its contents, because it is a dependency that you cannot easily exchange.

Access the singleton via the public property Instance.
Access the CurrentMDL_Constructor fields as follows:
CurrentMDL_Singleton.Instance.CurrentMDL_Excel
CurrentMDL_Singleton.Instance.CurrentMDL_Workbook
CurrentMDL_Singleton.Instance.CurrentMDL_Worksheet
CurrentMDL_Singleton.Instance.CurrentMDL_xlRange

Thanks to all who helped with this. I was able to figure out where my problems mostly originated from, which was with the layout of the Singleton class.
I want to mention my reasoning for using this Singleton class. I need to ensure only one instance of these Excel variables exists. This is important because my ViewModel and Model depend on referencing instances of the same items. I have been struggling with closing these Excel files because I was mixing up instances. These Excel files are very large, need to remain open in between application functions and close directly after the second function. The Singleton design model solves the problem of ensuing a single instance, and also allows me to access the instance from within my Model very effortlessly.
Knowledge Check : Where I Went Wrong:
My previous understanding was that the private constructor within the Singleton class would set up what I would need to reference after the Singleton was instantiated. This was the wrong thinking.
Don't use the private constructor to instantiate or reference anything; this goes against the main use of the Singleton class. All we're trying to do is make sure only one instance of this Singleton exists; the pivate constructor is there to solely create the Singleton Instance to reference later.
The Fix :
Remove "CurrentMDL_Constructor" class, pull the items that were in that class, which I was trying to create a reference for, into the Singleton main class.
public class CurrentMDL_Singleton
{
public Microsoft.Office.Interop.Excel.Application CurrentMDL_Excel { get; set; }
public Microsoft.Office.Interop.Excel.Workbook CurrentMDL_Workbook { get; set; }
public Microsoft.Office.Interop.Excel.Worksheet CurrentMDL_Worksheet { get; set; }
public Microsoft.Office.Interop.Excel.Range CurrentMDL_xlRange { get; set; }
private static CurrentMDL_Singleton instance = null;
private CurrentMDL_Singleton() {}
public static CurrentMDL_Singleton Instance
{
get
{
if(instance == null)
{
//Create a new instance
instance = new CurrentMDL_Singleton();
}
return instance;
}
}
}
CurrentMDL_Excel, CurrentMDL_Workbook, CurrentMDL_Worksheet, etc. are now all accessible through calling out the instance within the Singleton (thank god). Within my Model, I'm now able to to the following:
> CurrentMDL_Singleton.Instance.CurrentMDL_Excel = new Microsoft.Office.Interop.Excel.Application();
My next step is making this Singleton thread-safe.
Thanks again for the help, and I hope this helps someone else who is trying to understand how to implement Singletons.
-Chris

Related

Singleton Pattern - Default Property

I've been studying the Singleton pattern as it is used in the Settings class. Here's the relevant code from Settings.Designer.cs for my project AccessTest:
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
public string applicationSetting1
{
get
{
return ((string)(this["applicationSetting1"]));
}
}
}
What is unclear to me is why the property 'applicationSetting1' is accessed through another property 'Default' like this:
var value = AccessTest.Properties.Settings.Default.applicationSetting1;
I'm running VS2013 C# and 4.5.
Because the defaultInstance is static, whereas applicationSetting1 is not. This effectively makes defaultInstance your manager of the class instance. When you call a static method on a class, it doesn't need instantiating,, so you know that you can maintain only a single instance of the class.
Responding to your comments:
Default is NOT the parent of applicationSetting1; Default is simply a global function that returns an instance of applicationSetting1. In the case of a singleton pattern, that always happens to be the same instance.
Manager is my term. To better describe what a singleton pattern is, think of it as a global variable with a single accessor (which I was describing as a manager, simply because it manages the lifecycle of the variable).
Normaly, your Default property is called Instance
So that you can call your singleton like this :
Settings.Instance. X FUNCTION()
Design Pattern by Erich Gamma is pretty solid on design pattern. You should be able to find a PDF on the web easily :)
BTW you should also add this to your Default/Instance property
If(defaultInstance == null)
{
defaultInstance = new Settings();
}
return defaultInstance
That way your singleton is never null and is lazy instantiated
There are a great many posts on the singleton pattern but I couldn't find any that address this particular issue. So I thought I'd take a shot at explaining it myself using this example that I created in my secret laboratory with the help of your posts:
namespace MyProject.Properties
{
internal class Singleton
{
// Create an instance of the class itself.
private static Singleton instance = new Singleton();
// Wrap the instance in a public property.
public static Singleton Instance
{
get {return instance;}
}
// Prevent additional references from being created with a private constructor.
private Singleton() { }
// Create a non-static variable.
public string nonStatic = "non static";
}
}
We know the following about this Singleton class:
The 'Instance' public property can only be accessed statically.
'nonStatic' can't be accessed statically, i.e., it can only be
accessed via a reference.
The private constructor prevents additional
references from being created.
How, then, is it possible to access 'nonStatic' from outside the class?
The framework resolves the dilemma by endowing the static 'Instance' with magical powers that only exist in a singleton situation: 'Instance' becomes a "bridge" that provides access to any non-statics. Ergo, this form works:
var value = MyProject.Properties.Singleton.Instance.nonStatic;
Note: The pattern used my Microsoft in the Settings.Designer.cs file appears to not be a true singleton because the default constructor allows additional references to be created.

Where to place global variables in MVVM (Caliburn micro)

I'm refactoring a program done in WinForms to WPF and I'm using Caliburn.Micro as a framework to implement the MVVM pattern.
In the old program, I use a StatisHelper class to allow different static variables like the theme, the language, the username or the rights of access, etc ..
I know that it could be insecure because these variables are public, but I doubt that my end users know how to access these values...
Anyway, I would like to know the best practice in MVVM to save global values (in concrete, I'm using Caliburn.Micro framework) that can be accessed for all the view-models.
Thank you for your responses.
You could use a singleton class (frowned upon by some). Note that the constructor is private, so nothing else can create an instance. Use the Instance property to access it. The Instance property in this example will only construct the singleton object the first time it's accessed.
To use it, simply do something like var foo = Globals.Instance.SomeProperty.
Note that this has nothing to do with WPF or MVVM, and could have been used in WinForms as well.
public class Globals {
private Globals _Instance;
public Globals Instance {
get {
if (_Instance == null)
_Instance = new Globals();
return _Instance;
}
}
private Globals() {
}
public string SomeProperty { get; set; }
}
I use a custom StateManager class that implements the Singleton pattern so that there is only one of these instances in the application:
public class StateManager : INotifyPropertyChanged
{
private static StateManager instance = new StateManager();
/// <summary>
/// Initialises a new empty StateManager object.
/// </summary>
public StateManager() { }
/// <summary>
/// Gets the single available instance of the application StateManager object.
/// </summary>
public StateManager Instance
{
get { return instance; }
}
...
}
This is then referenced in my base view model, so that all of my view models have access to it:
public StateManager StateManager
{
get { return stateManager.Instance; }
}
Furthermore, because it is referenced in my view model classes, I can also Bind to the values in XAML:
<Window Title="{Binding StateManager.WindowTitle, Mode=OneWay}" ... />
Well my answer is a combination of ideas from the #Steve and #Sheridan and the link in the comment.
First of all, I have to say separate the data from the code.
As for the data, I would use those Resx files to store all those kinds of resources, whether they are binary resources like simple audio files, images, localizable strings, etc .., because this makes it easy to swap them at run-time.
As for the code, I would use a collection like IConfigurationProvider like this:
public interface IConfigurationProvider {
GetResourceByName<T>(string key); // T is the type of the requested resource
// THIS IS A SIMPLIFIED VERSION, YOU CAN HAVE MORE METHODS
// ACCORDING TO YOUR NEEDS
}
The implementation of this interface could use the Resx files to store and retrieve resources, then you can inject those resources into the different classes that need it.
This haves some advantages like:
Better testability
Can use different media to store the resource data without changing the interface
Swap the implementation at run-time, you can use DI now.
More clear where is the data coming from

Storing global immutable data in static classes

I have a WinForms project, which uses a lot of user controls. Some of these user controls use classes from business logic layer. These classes are mainly performing CRUD operation to a database (through data access layer) plus some additional validation and reporting.
The project uses some common objects (logged user, some controllers and validators), which are instantiated in main form and then injected into child user controls via initialization methods or public properties. This means, that I have a lot of code, which just passes these common objects from parent control to child controls.
In order to avoid this, I could create a static class (ApplicationContext for example) and save all common controls into it. This would happen in the main form and all other user controls or forms in the project could use it.
I see that this pattern is discouraged in general (storing some global data in static classes). But what if this data is immutable? Is this approach ever a good idea?
Or do you know any other approach, which could help me get rid of all the initialization code?
You can use an Inversion of Control container like Unity or Autofac and have it automatically wire up your object graph for you.
You can have each object that requires any one of the common objects define a dependency to their interfaces, either though a constructor argument, or as a public property, and the IoC container will wire the appropriate objects together.
Property injection example with Unity:
public class MyUserControl : UserControl
{
[Dependency]
public LoggedUserService UserService { get; set; }
public void Method()
{
// the IoC container will ensure that the UserService
// property has been set to an object
}
}
All you do in the main form is registering the common objects you want the IoC container to know about and then you ask for the root object. The object graph will be assembled magically for you and you don't have to to all the wire code nor care how it is done.
You can use a dependency injection / ioc container for maintaining your global objects.
I have made good experience with the autofac library but there are many other available.
When using setter injection, all of your controls get set dependent objects set automatically.
You'll want to use Singletons for this situation. Singletons will allow you to use the same instance of your object, more safe and flexible than static.
public sealed class Singleton
{
public object Property1 {get;set;}
public void Method1 (){}
static Singleton instance = null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
then you can use it like you would static, but a bit different...
public class Main
{
public Main()
{
Singleton.Instance.Property1 = "somevalue";
Singleton.Instance.Method1();
}
}
You can use a static class to store some immutable data - no problem with this.
How ever if you want to store controls there it might not work as expected.
For example method like OnDataBinding and Render.

Declaring a Class as a Member of itself

I was working in the Microsoft.Ink dll recently using C# and was debugging a problem (which is not related to this) I noticed, that when I was debugging it, ink objects had a strokes object, which had an ink object, which had.... etc.
This confused me, as I was under the assumption you could not do this (I come from a C++ Background)
But I ignored it, solved the problem, and moved on. Today, I run into a similar problem, as I look at a class which had a private member which was the same class as itself.
public sealed class Factory
{
private static Factory instance = new Factory();
}
How is that even possible? I can now call instance.instance.instance.instance...etc. This, as you can imagine, hurts my mortal brain, and I'm sure it can't be good on the computer either. How does the compiler deal with this? And Just how deep does the rabbit hole go?
Because it's static and therefore there is only one copy of the variable instance within the AppDomain.
What you're thinking of is this:
public class Foo
{
private Foo lol = new Foo();
}
Notice, everything here is instance, not static.
As the commenters noted (long ago), this is valid syntactically, but would result in a StackOverflowException being thrown, as the assignment requires construction, and construction creates a new assignment. One triggers the other in a cycle that ends when the call stack reaches its maximum length.
In OP's example, assignment requires construction, but the assignment is triggered by the static constructor, not the instance constructor. The static constructor only executes once within an AppDomain, in order to initialize the class' Type. It isn't triggered by instance construction, and so (in OP's example) won't result in a stack overflow.
it's not necessarily recursive by nature. think of a linked list. or a tree.
class Directory
{
string name;
Directory parentDirectory;
}
It's just allows objects of that class to have an internal reference to another object of that class.
This is a software pattern known as "Singleton".
Some people frown upon the use of the pattern for more reasons than just stated in the question but for better or for worse it is a common pattern in the .NET Framework. You will find Singleton Properties (or fields) on classes that are meant to be instantiated only once. Think of a static Instance property as a global hook upon which to hang an object.
Since this is a class, and not a struct, when you declare a field that is the class, you are only defining a reference to a class. This allows you to keep having references, provided you assign them.
In your case, you're reference allocates a new class, but it is static, so it's only going to do it one time, no matter how many classes you create. The instance constructor runs the first time Factory is used, and will call a single non-static constructor. Doing instance.instance.instance is not allowed, since instance is static. You cannot access a static variable from a member - you need to do Factory.instance.
However, you ~could~ make instance non-static, and have it be a reference to some other "Factory" class, or even a reference to this. In that case, you could chain instance.instance.instance - but it will just follow the references as long as you've set them. Everything works, no problems.
There will only ever be one instance of 'instance' because it is static. The only way you should be able to access it is by calling Factory.instance.
string text = Factory.instance.ToString(); // legal
string text2 = Factory.instance.instance.ToString(); // compiler error
I think you should ask the other way around: Why shouldn't this be possible? Factory is just a type like any type which gets resolved by the compiler.
As most of the answers here point out that this is working only because Factory is a static field, I have added the following sample. Please note that this is a very primitive sample of a chained list (you probably wouldn't implement it that way for various reasons, but I didn't come up with a better example yet). In this example, ChainedListItem is a container for an element of a single-linked list, which contains a field of the very same type to point to the next item in the list. The list has an (empty) head element and the last element is marked by having an empty _nextItem field:
public class ChainedListItem<T>
{
private ChainedListItem<T> _nextItem;
T _content;
public ChainedListItem<T> NextItem
{
get { return _nextItem; }
set { _nextItem = value; }
}
public T Content
{
get { return _content; }
set { _content = value; }
}
public ChainedListItem<T> Add(T content)
{
_nextItem = new ChainedListItem<T>();
_nextItem.Content = content;
return _nextItem;
}
public void Dump()
{
ChainedListItem<T> current = this;
while ((current = current.NextItem) != null)
{
Console.WriteLine(current._content);
}
}
}
class Program
{
static void Main(string[] args)
{
ChainedListItem<int> chainedList = new ChainedListItem<int>();
chainedList.Add(1).Add(2).Add(3);
chainedList.Dump();
}
}
The "rabbit hole" goes as deep as your stack space allows you to make another call to the constructor of the type. If you try to go deeper than that, you will get a stackoverflow exception as with any other recursion.
By the way, the code that you wrote in your answer is showing a very basic implementation of a Singleton which is actually based on having a (private) static member of the same type as the surrounding type.
And, last but not least, such constructs are also perfectly fine in C++.
It is a singleton. Meaning there is really only one instance of the class.
Is that the entire class? Typically in C# you will see a singleton like
public class SomeClass
{
static readonly SomeClass instance = new SomeClass();
public static SomeClass Instance
{
get { return instance; }
}
static SomeClass()
{
}
SomeClass()
{
}
}
I'm not sure how you would even access the instance since it is private. The only thing this would be useful for is a Singleton implementation, but if that is the case you are mission the public property exposing the instance.
This is done all the time is most OO languages. instance is a static member of Factory. There is nothing unusual about this code. It is standard Factory pattern. Do you also have a problem with code like this?
x = x + 1;

Singleton with a public (single-instance) constructor

As an exercise, I'm translating parts of our large and battle-hardened Delphi-framework to C#.
Included in this framework is a generic singleton parent class. Of course, implementing a singleton in C# is fairly easy (there is even a Jon Skeet article, so what more could I wish for), but our Delphi singleton has a slightly different take on the pattern: as opposed to publishing an 'instance' property/method, it has a "fake" constructor that always returns the same instance. The essential characteristic of this approach is that the user of the singleton class doesn't know that he is dealing with a singleton:
as far as they know, they just construct any old class and request some information from it.
I want to accomplish the same thing in C# (as an exercise, so it doesn't have to be production-quality code, evil hackery is fine), but so far I've failed.
Any suggestion to make a simple myInstance = new MyClass(); always return the same instance is most welcome!
Additional info
We are talking a convenience-implementation of the singleton pattern, as offered by the framework. It doesn't necessarely have to be a parent-class, but it does have to assist the developers in creating their own singletons as well. Requiring them to manually redirect all their method calls to the single-instance will not make them overflow with joy. :-)
I'm not really interested in debating whether or not this is the right way to deal with singletons, for now I'm just interested in the finer art of c#-tweaking.
You would do a Proxy (Edit: As Tom points out below, the proper design pattern is Monostate):
public class MyClass {
MyActualClass _actual;
public MyClass() {
_actual = MyActualClass. Instance;
}
public DoStuff() {
_actual.DoStuff();
}
}
internal class MyActualClass {
private MyActualClass {
}
public DoStuff() {
...
}
MyActualClass _instance;
public static Instance {
get {
if(_instance == null)
_instance = new MyActualClass()
return _instance;
}
}
}
....
public static void Main() {
var my1 = new MyClass();
var my2 = new MyClass();
}
my1 != my2 but my1.DoStuff() calls the same instance of the method as my2.DoStuff()
This would be simplified even further if you programmed of an interface only.
Edit: The equality problem could partially be solved by making _actual protected internal and overwriting MyClass.Equals(object obj) to check whether this._actual == obj._actual
I believe the Monostate pattern will give you what you need:
"The Monostate gives us the singularity of state that we so treasure in the Singleton, but without all of the static headaches that come along with it."
More here:
http://jeremyjarrell.com/archive/2008/04/21/88.aspx
As far as I know, this cannot be done for real because of how C# handles object instances. In order for a constructor to be called, the instance has to actually be created, and you can't just "return" another object from a constructor.
The best thing I can come up with (other than using a factory method) is to treat the class internally as a Singleton, and create "dummy" instances that all just point back to that original instance, when created. So for example, in your constructor you would check to see if the singleton has been initialized, and if not, would initialize it, then you would basically just proxy each instance's methods and properties back to the singleton.
In this implementation, the singleton needn't even be necessarily the same class, but you could if you wanted to keep things contained.
Update: One drawback of this approach is that although each instance would behave as a singleton, it would still have its own object reference and therefore you might also want to override Equals() for equality comparisons.
I think you could possibly roll something with Remoting.
Update:
A better way would be to wrap a proper singleton class in a struct or lightweight class.
Create the singleton as a static member and make all methods access the single static instance.
class SingletonWrapper {
private static RealSingleton instance = new RealSingleton();
public void methodA() {
instance.methodA();
}
public String getA() {
return instance.getA();
}
}
(This is actually Java code but C# is similar enough, I think. :)
I don't see how you can, as constructors don't use a return statement. You could clone all of the relevant links to the singleton, but it would have local copies of local variables, and be very messy.
Instead have the constructor check if the singleton is instantiated, and if it has been already, throw an exception, or log a warning to the developer who is using the old style code.
How about using a static function to return an object insted of using the new keyword.
static private m_obj my_obj;
static private bool my_new_obj;
static public m_obj create_m_obj()
{
if (my_new_obj == false)
{
my_new_obj = true;
my_obj = new my_obj();
}
return my_obj;
}
Then you have easy full controle over the creation of the object, if I an not mistaken.

Categories