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.
Related
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
I have some code as shown below. I guess it is Singleton pattern. Why do I need a static constructor. Also what is the advantages of this? Thanks for your reply ...
public sealed class Myclass
{
static Myclass()
{
Myclass.Application = new Myclass();
}
protected Myclass()
{
}
static Myclass _application;
public static Myclass Application
{
get { return Myclass._application; }
protected set { Myclass._application = value; }
}
string _name;
public string Name
{
get { return _name}
protected set { _name= value; }
}
}
To start with, this class is somewhat odd for having a protected constructor. It's not a fatal flaw given that it's sealed, but it's distinctly odd.
There's a potential difference in timing between this code and the nearly-equivalent use of a static variable initializer:
static readonly Myclass _application = new Myclass();
(There's no need for a setter in this case, of course.)
You can't do that with an automatically implemented property though.
Using static initialization in some form gets you "free" thread-safety - you don't need to do any locking in order to get lazy initialization.
You may find my singleton implementation article interesting for more options.
Usage of a type ctor here is a guarantee that singleton instance will be initialized once. It's more simple that double-checked lock pattern, when implementing lazy singleton initialization, but it has disadvantage the same reason - singleton creation may be very expensive, and singleton may never be used during app lifetime.
There is no immediate advantage in the static constructor as opposed to a lazy-instantiated on get approach, other than thread safety as pointed out by Jon Skeet's answer. This may or may not be relevant in your situation, though you don't specify anything. It just makes the code look different, but is going to result in the same functionality.
The "advantage" of the singleton pattern is that is allows easy access to a single instance of a class, basically a sort of "globally" accessible instance of the class.
I say "advantage" as there are many discussions about the Singleton pattern being an anti-pattern. I am on the fence. In a small application this can function OK and most of the proposed alternative solutions involve Dependency Injection frameworks (often sometimes with the life-span of "Singleton"!), which may be impractical on smaller apps.
Just a note, having a sealed class with protected members is pointless - sealed classes cannot be inherited.
If you write in this way you can use auto property and do not actually implement it.
Say like this:
public sealed class Myclass
{
static Myclass()
{
Myclass.Application = new Myclass();
}
.....
public static Myclass Application {get;set;}
...
}
Basically, there is no any practcal advantage if not like this one: code-style.
You have to create the instance of the class somewhere, and that can either be in a static constructor, or in the property that gets the instance.
Anyhow, it's not a good code example that you have found.
It has protected members even though it's sealed, which only makes the code confusing. They should be private.
If you look at the Name property you will notice that it's impossible to set it, so it will always be null.
static constructor it gets called during the loading of the assembly...
EDIT:
thanks jon I was wrong...
now i understand static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced..
I was researching on the singleton pattern for C# I found this example from the msdn website.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Because the Singleton instance is
referenced by a private static member
variable, the instantiation does not
occur until the class is first
referenced by a call to the Instance
property. This solution therefore
implements a form of the lazy
instantiation property, as in the
Design Patterns form of Singleton.
I am not pretty sure when will the memory will get allocated to
private static readonly Singleton instance
1)Will it happen when the Instance property is called or even before it?
2) I need to force the class to create a new memory sometimes to purge its content. Is it safe to do so using set ?
set
{
instance = null;
}
In the example code you provided, the singleton instance will be created at the time of the first access to the class. This means for your example at the time when Instance gets called for the first time.
More insight you can find in Jon Skeet's article Implementing the Singleton Pattern in C#, see Method 4.
Basically, in order to achieve truly lazy behaviour something like
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton(){}
private Singleton(){}
public static Singleton Instance
{
get { return instance; }
}
}
is enough.
(But anyway, the full and much better overview can be found in the mentioned article.)
EDIT
Actually, as it follows from the mentioned article, the instance is not guaranteed to be created at the first access, because of BeforeFiledInit mark. You need to add an empty static constructor, this way it's guaranteed to be lazy. Otherwise the instance will get created at some unspecified time between the program start and first access. (.NET runtime 2.0 is known to have more eager strategy, so you'll probably not get the lazy behaviour.)
Quoting from the said article:
The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler [...] marks all types which don't have a static constructor [...] as beforefieldinit.
EDIT 2
If you want the singleton object to clean up, you should include this functionality into the class Singleton itself.
Removing the property value will effectively make your class not a singleton any more! Imagine that someone accesses the singleton and gets the singleton instance. After that you set the property to null. The existing object of the Singleton class won't disappear, because there's still a reference to it! So the next time you access the Instance property, yet another instance of the Singleton class would be created. So you lost two things: your object is not a singleton any more (because you have got 2 instances existing at the same time), and the memory hasn't been cleared either.
The singleton instance will be loaded into memory when the class itself is loaded which is when the method which could call it begins execution. The actual line that calls into the class doesn't have to actually execute. This is a very slight distinction but can create hard-to-debug problems when a static constructor or static field initializer can throw an error (which you don't have here).
This is fixed in .NET 4 with the new Lazy<T> implementation.
http://msmvps.com/blogs/jon_skeet/archive/2010/01/26/type-initialization-changes-in-net-4-0.aspx
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
http://csharpindepth.com/Articles/General/Singleton.aspx
The C# specification says:
10.5.5.1 Static field initialization
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.
i.e. They only guarantee you get is that it happens before the instance field is read. But it can happen much earlier.
If you want to guarantee that it that it doesn't run earlier than the first access of the property you'll need to add a static constructor(potentially empty):
The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
· An instance of the class type is created.
· Any of the static members of the class type are referenced.
As a side node: I noticed that when using DI it is rarely necessary to use an actual singleton. Simply telling DI that it should create a single instance is enough. This is very nice if you decide at a later point that you want more than one instance, since then the fact that it's a singleton isn't baked into all the code using it.
It says in the quote you posted:
the instantiation does not occur until
the class is first referenced by a
call to the Instance property
So... Whenever you call .Instance, or at some point before.
Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called.
Read more on MSDN
In a web app, I need to have only one instance of a class called ProcessManager. One way is to make it a singleton. The other way is to use the HttpApplicationState to make sure I always access the same instance, like this:
public static ProcessManager ProcessManager
{
get
{
HttpApplicationState applicationState = HttpContext.Current.Application;
if (applicationState["ProcessManager"] == null)
{
applicationState["ProcessManager"] = new ProcessManager();
}
return (ProcessManager)applicationState["ProcessManager"];
}
}
Which method is better and why?
Based on the limited description you've given, I would choose a Singleton, because then it doesn't have a dependency on HttpContext.Current, and can be used outside of the ASP.Net pipeline (for example, when you want to write unit tests.)
(As an aside, when you set something into ApplicationState, you also need to first call Lock() on it, and then Unlock() it after you're done writing to it, to make sure it's thread safe.)
Alternately, allow injection of an HttpContext when you create your ProcessManager, such that you can use it with a mocked HttpContext.
if you plan to implement it as singleton,as per Jon Skeet (a.k.a C# guru),he personally prefers the code below
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
(I'm assuming your ProcessManager constructor is private.)
Making it an actual singleton would be best, because such an approach would make it structurally impossible for other programmers that are maintaining your code to accidentally create multiple instances. There's nothing stopping a consumer from accessing the HttpApplicationState directly and removing and replacing the ProcessManager instance. So you must rely on convention to protect the instance of ProcessManager in HttpApplicationState.
Only if there is an actual use case for multiple instances of the class to exist does it make sense to allow multiple instantiations while relying on convention to protect the instance in HttpApplicationState.
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.