I have the following code in a class library:
public class Manager
{
private static readonly Manager instance = new Manager();
public static IHelper Helper { get { return Manager.instance.helper; } }
[Import(typeof(IHelper))]
internal IHelper helper { get; set; }
private Manager()
{
using (DirectoryCatalog catalog =new DirectoryCatalog(#"c:\Dev\Plugins"))
{
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
}
I am using the above class to set custom user-interface settings at run-time, will the constructor run every time I access a member (will it scan the directory)?
An example call might be lblMask.Text = Helper.SearchMask;
The directory scanning only happens in the instance constructor. The instance constructor only happens when new Manager() is used (assuming nobody cheats with reflection), which only happens once, in the static field initializer.
So: no. It should only happen once - the first time per app-domain.
However, you could just stick in a break-point / some kind of output, and find out...
When you access the Manager class for the first time (either an instance of it or its static methods and fields), the static constructor of Manager will run and initialize the instance field.
So the next time you access the instance field, it is initialized and won't run new Manager().
In fact the C# compiler will automatically move the fields initializations to the class constructor. The following code
private static readonly Manager instance = new Manager();
will be converted to this:
private static readonly Manager instance;
static Manager()
{
instance = new Manager();
}
Related
I have noticed a rather weird behaviour in my application I am creating;
I have a class I defined that has a static "instance" variable of the class type.
I would assume that (as per code attached) the constructor would be called.
Alas, it is not, unless I use the Void.get in a non-static field anywhere in my code.
public class Void : TilePrototype {
public static Tile get = new Tile((int)TileEntities.Void);
public static Void instance = new Void();
public Void() {
Debug.Log("created");
id = (int)TileEntities.Void;
isBlocking = true;
register();
}
public override RenderTile render(Tile tile){
return new RenderTile(0, new Color(0, 0, 0, 0));
}
So when I have something like :
public static TileStack empty = new TileStack(Void.get, Void.get);
the Void class constructor never gets called. But, if I have:
Tile t = Void.get;
Anywhere in my code it will be called.
Why?
Thanks.
This is a really really subtle and nuanced area of C#; basically, you've stumbled into "beforefieldinit" and the difference between a static constructor and a type initializer. You can reasonably ask "when does a static constructor run?", and MSDN will tell you:
It is called automatically before the first instance is created or any static members are referenced.
Except... public static TileStack empty = new TileStack(Void.get, Void.get); isn't a static constructor! It is a static field initializer. And that has different rules, which basically are "I'll run when I must, no later, possibly sooner". To illustrate with an example: the following will not (probably) run your code, because it doesn't have to - there isn't anything demanding the field:
class Program
{
static void Main()
{
GC.KeepAlive(new Foo());
}
}
public class Foo
{
public static TileStack empty = new TileStack(Void.get, Void.get);
}
However, if we make a tiny tweak:
public class Foo
{
public static TileStack empty = new TileStack(Void.get, Void.get);
static Foo() { } // <=== added this
}
Now it has a static constructor, so it must obey the "before the first instance is created" part, which means it needs to also run the static field initializers, and so on and so on.
Without this, the static field initializer can be deferred until something touches the static fields. If any of your code actually touches empty, then it will run the static field initializer, and the instance will be created. Meaning: this would also have this effect:
class Program
{
static void Main()
{
GC.KeepAlive(Foo.empty);
}
}
public class Foo
{
public static TileStack empty = new TileStack(Void.get, Void.get);
}
This ability to defer execution of the static initialization until the static fields are actually touched is called "beforefieldinit", and it is enabled if a type has a static field initializer but no static constructor. If "beforefieldinit" isn't enabled, then the "before the first instance is created or any static members are referenced" logic applies.
Thanks to Marc Gravell's aswer I came up with this contraption (and admittedly I do like the new solution more than the old one, so thanks again!)
Modifications done to the Void class:
public class Void : TilePrototype {
public static Void instance = new Void();
public static Tile get {
get {
return new Tile(instance.id);
}
}
public Void() {
isBlocking = true;
}
public override RenderTile render(Tile tile){
return new RenderTile(0, new Color(0, 0, 0, 0));
}
}
So as You can see I made the "get" variable a property, so that it's evaluated later, when you actually need the tile, not on construction.
I've changed all "get"s this way.
Second change is in the TilePrototype:
public class TilePrototype {
public static Dictionary<int, TilePrototype> tilePrototypeDictionary = new Dictionary<int, TilePrototype>();
public static void registerPrototype(int id, TilePrototype tp){
tp.id = id;
tilePrototypeDictionary.Add(id, tp);
}
public static bool registered = false;
public static void registerAll(){
if( registered ) return;
registerPrototype(0, Void.instance);
registerPrototype(1, Air.instance);
registerPrototype(2, Floor.instance);
registerPrototype(3, Wall.instance);
(...)
Here I've added the registerPrototype and registerAll functions.
This gives me easy access to all the registered type ids (by say Wall.instance.id) as well as the other way around (from id to instance via the Dictionary)
I also have all registered things in one place, with the possibility of runtime adding more
Overall, much neater, and here I assure that all tiles are registered properly and assigned proper IDs.
Change of ID is simple and in one place and everywhere else, access to this ID is done via a short .instance.id
Thanks again for the help :)
My friend told me that the following is one of the ways to create singleton design pattern in C#
public class class1{
public static class1 Obj { get; private set; }
static class1()
{
Obj = new class1();
}
}
He told me that the static constructor runs only one time in application, so only one instance of class1 will be created,
but I see that I have to add this if(Obj==null) to check the existence of object
public class class1{
public static class1 Obj { get; private set; }
static class1()
{
**if(Obj==null)**
Obj = new class1();
}
}
which code is correct?
Assuming that the only place where Obj is set is in the static constructor, the first code snippet is correct; the second code snippet is redundant.
Since static constructors run only once per class. If there is no other path to set Obj, its value will always be null at the beginning of the static constructor. Therefore, the check if(Obj==null) will always succeed, which makes it redundant.
The static constructor will only ever be called once, at some point prior to the static variables being allocated.
Which means that your friend is correct, you do not need the if statement - it is redundant.
This is because you cannot call a static constructor manually, it will only be called once, at the start of run-time.
Further reading : https://stackoverflow.com/a/4506997/617485
Edit: My bad, no strage events behavior. Error was somewhere else in code. Thx everybody for help. Please ignore this question
Please can someone explain to me what is happening here. I'm experiencing an unexpected event behaviour.
There is a singleton class:
internal class QueueListener
{
private static readonly object QueueChangeLock = new object();
private readonly List<IQueuedJobExecutioner> jobsQueue = new List<IQueuedJobExecutioner>();
// Here comes singleton private constructor, Instance property, all classic.
// Important line in constructor is this:
QueueManager.NewJobQueued += NewJobQueuedHandler;
private void NewJobQueuedHandler(object sender, NewJobQueuedEventArgs args)
{
lock (QueueChangeLock)
{
// This is the problematic place, note this!
jobsQueue.Add(args.QueuedJobExecutioner);
}
}
}
Now there is a second class:
public class QueueManager
{
public static event NewJobQueuedEventHandler NewJobQueued;
protected void RaiseNewJobQueuedEvent(IQueuedJobExecutioner queuedJobExecutioner)
{
if (NewJobQueued != null)
{
NewJobQueued(this, new NewJobQueuedEventArgs { QueuedJobExecutioner = queuedJobExecutioner });
}
}
}
Both classes reside on a server. Via WCF calls client executes sth like new QueueManager().MyMethod(), which calls RaiseNewJobQueuedEvent.
Everything works fine, however if two events are raised almost at the same time, I see in debugger the following at the problematic place (see comment in QueueListener):
First event comes. jobsQueue has no members.
jobsQueue.Add() is executed. jobsQueue has 1 member.
Second event comes. jobsQueue has no members! How? It's in a singleton and we just added a member!
jobsQueue.Add() is executed. jobsQueue has 1 member. Again. Member added in step 2 has been lost.
Not judging the design itself (it has some "historical" reasons), why exactly is this happening? Is this expected behavior and event somehow gets at some point a snapshot of jobsQueue or this is nonesense and I'm just missing some part of the puzzle?
Edit:
I'd say it is a singleton, and is implemented like this (these lines were omitted in original post):
class QueueListener
{
private static readonly object SyncRoot = new object();
private QueueListener()
{
//...
}
public static QueueListener Instance
{
get
{
if (instance == null)
{
lock (SyncRoot)
{
if (instance == null)
{
instance = new QueueListener();
}
}
}
return instance;
}
}
}
Yuval is correct, your class is not a singleton. A singleton is created when you have a public static method to create an instance and a private constructor. The private constructor ensures that the only way to create an instance is through the public method.
Please see https://msdn.microsoft.com/en-us/library/ff650316.aspx for more details.
Your QueueListener class is not actually a singleton. What that means for you is that you are creating multiple instances of it. To fix that you have to add the static keyword in the class declaration and declare a static constructor as well. Try changing your class to what is shown below:
internal static class QueueListener
{
private static readonly object QueueChangeLock = new object();
private static readonly List<IQueuedJobExecutioner> jobsQueue = new List<IQueuedJobExecutioner>();
// This is the singleton constructor that will be called
static QueueListener()
{
// Here comes singleton private constructor, Instance property, all classic.
// Important line in constructor is this:
QueueManager.NewJobQueued += NewJobQueuedHandler;
}
// Rest of class code...
}
I have a singleton class, it is reading config file.
public sealed class SettingsHelper
{
private static readonly SettingsHelper _Instance = new SettingsHelper();
static SettingsHelper()
{
}
public static SettingsHelper Instance
{
get
{
return _Instance;
}
}
private NameValueCollection _SettingsSection = null;
public SettingsHelper()
{
_SettingsSection = new NameValueCollection(ConfigurationManager.AppSettings);
}
.....
}
}
But if config file getting changed the singleton do not picking up the change.
Is there any way to recreate the instance of singleton(call its constructor) or i should create separate method which will be reinitiating the instance of singleton?
You're trying to throw away the very first purpose of singleton pattern. A singleton is there, just to prevent any other code from instantiating a new instance of that class. To make a singleton class, you should not have public constructors at all. You already have a public constructor.
I encourage you to read the first line, just the first line of this Wikipedia article about Singleton Pattern.
What you're trying to do, is called cache dependency in C#. You're trying to cache Web.config's app settings and you are dependent on Web.config's change. You should search that.
Recreating a singleton is abad idea - references to the 'old' singleton will stay.
So it's no longer a singelton!
In your case I would create new settings. Why not make a public method LoadSettings() and call that?
public sealed class SettingsHelper
{
private static readonly SettingsHelper _Instance = new SettingsHelper();
private NameValueCollection _SettingsSection = null;
// ...
private SettingsHelper()
{
LoadSettings()
}
public void LoadSettings()
{
_SettingsSection = new NameValueCollection(ConfigurationManager.AppSettings);
}
.....
}
}
BTW: make SettingsHelper() private...
It will be better to create a separate method inside your singleton class to read the settings again. Obviously, with this approach, you will have to call this method from your code.
How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.
If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.
public static class GlobalSomething
{
public static int NumberOfSomething { get; set; }
public static string MangleString( string someValue )
{
}
}
Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.
Singletons only make sense if both of these conditions are true:
The object must be global
There must only ever exist a single instance of the object
Note that #2 does not mean that you'd like the object to only have a single instance - if thats the case, simply instantiate it only once - it means that there must (as in, it's dangerous for this not to be true) only ever be a single instance.
If you want global, just make a global instance of some (non signleton) object (or make it static or whatever).
If you want only one instance, again, static is your friend. Also, simply instantiate only one object.
Thats my opinion anyway.
Singleton != Global. You seem to be looking for the keyword static.
You can really simplify a singleton implementation, this is what I use:
internal FooService() { }
static FooService() { }
private static readonly FooService _instance = new FooService();
public static FooService Instance
{
get { return _instance; }
}
Hmm, this all seems a bit complex.
Why do you need a dependency injection framework to get a singleton? Using an IOC container is fine for some enterprise app (as long as it's not overused, of course), but, ah, the fella just wants to know about implementing the pattern.
Why not always eagerly instantiate, then provide a method that returns the static, most of the code written above then goes away. Follow the old C2 adage - DoTheSimplestThingThatCouldPossiblyWork...
I would recommend you read the article Exploring the Singleton Design Pattern available on MSDN. It details the features of the framework which make the pattern simple to implement.
As an aside, I'd check out the related reading on SO regarding Singletons.
Ignoring the issue of whether or not you should be using the Singleton pattern, which has been discussed elsewhere, I would implement a singleton like this:
/// <summary>
/// Thread-safe singleton implementation
/// </summary>
public sealed class MySingleton {
private static volatile MySingleton instance = null;
private static object syncRoot = new object();
/// <summary>
/// The instance of the singleton
/// safe for multithreading
/// </summary>
public static MySingleton Instance {
get {
// only create a new instance if one doesn't already exist.
if (instance == null) {
// use this lock to ensure that only one thread can access
// this block of code at once.
lock (syncRoot) {
if (instance == null) {
instance = new MySingleton();
}
}
}
// return instance where it was just created or already existed.
return instance;
}
}
/// <summary>
/// This constructor must be kept private
/// only access the singleton through the static Instance property
/// </summary>
private MySingleton() {
}
}
Static singleton is pretty much an anti pattern if you want a loosely coupled design. Avoid if possible, and unless this is a very simple system I would recommend having a look at one of the many dependency injection frameworks available, such as http://ninject.org/ or http://code.google.com/p/autofac/.
To register / consume a type configured as a singleton in autofac you would do something like the following:
var builder = new ContainerBuilder()
builder.Register(typeof(Dependency)).SingletonScoped()
builder.Register(c => new RequiresDependency(c.Resolve<Dependency>()))
var container = builder.Build();
var configured = container.Resolve<RequiresDependency>();
The accepted answer is a terrible solution by the way, at least check the chaps who actually implemented the pattern.
public class Globals
{
private string setting1;
private string setting2;
#region Singleton Pattern Implementation
private class SingletonCreator
{
internal static readonly Globals uniqueInstance = new Globals();
static SingletonCreator()
{
}
}
/// <summary>Private Constructor for Singleton Pattern Implementaion</summary>
/// <remarks>can be used for initializing member variables</remarks>
private Globals()
{
}
/// <summary>Returns a reference to the unique instance of Globals class</summary>
/// <remarks>used for getting a reference of Globals class</remarks>
public static Globals GetInstance
{
get { return SingletonCreator.uniqueInstance; }
}
#endregion
public string Setting1
{
get { return this.setting1; }
set { this.setting1 = value; }
}
public string Setting2
{
get { return this.setting2; }
set { this.setting2 = value; }
}
public static int Constant1
{
get { reutrn 100; }
}
public static int Constat2
{
get { return 200; }
}
public static DateTime SqlMinDate
{
get { return new DateTime(1900, 1, 1, 0, 0, 0); }
}
}
I like this pattern, although it doesn't prevent someone from creating a non-singleton instance. It can sometimes can be better to educate the developers in your team on using the right methodology vs. going to heroic lengths to prevent some knucklehead from using your code the wrong way...
public class GenericSingleton<T> where T : new()
{
private static T ms_StaticInstance = new T();
public T Build()
{
return ms_StaticInstance;
}
}
...
GenericSingleton<SimpleType> builder1 = new GenericSingleton<SimpleType>();
SimpleType simple = builder1.Build();
This will give you a single instance (instantiated the right way) and will effectively be lazy, because the static constructor doesn't get called until Build() is called.
What you are describing is merely static functions and constants, not a singleton. The singleton design pattern (which is very rarely needed) describes a class that is instantiated, but only once, automatically, when first used.
It combines lazy initialization with a check to prevent multiple instantiation. It's only really useful for classes that wrap some concept that is physically singular, such as a wrapper around a hardware device.
Static constants and functions are just that: code that doesn't need an instance at all.
Ask yourself this: "Will this class break if there is more than one instance of it?" If the answer is no, you don't need a singleton.
hmmm... Few constants with related functions... would that not better be achieved through enums ? I know you can create a custom enum in Java with methods and all, the same should be attainable in C#, if not directly supported then can be done with simple class singleton with private constructor.
If your constants are semantically related you should considered enums (or equivalent concept) you will gain all advantages of the const static variables + you will be able to use to your advantage the type checking of the compiler.
My 2 cent
Personally I would go for a dependency injection framework, like Unity, all of them are able to configure singleton items in the container and would improve coupling by moving from a class dependency to interface dependency.
You can make a simple manual static singleton implementation for your common (non-static) class by adding a static property Instance (name can vary) into it with initialization like this:
public class MyClass
{
private static MyClass _instance;
public static MyClass Instance => _instance ?? (_instance = new MyClass());
// add here whatever constructor and other logic you like or need.
}
Then it can be resolved anywhere from this namespace like this:
var myClass = MyClass.Instance; // without any new keyword
myClass.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticProperty = "new value";
By hiding public constructor, adding a private static field to hold this only instance, and adding a static factory method (with lazy initializer) to return that single instance
public class MySingleton
{
private static MySingleton sngltn;
private static object locker;
private MySingleton() {} // Hides parameterless ctor, inhibits use of new()
public static MySingleton GetMySingleton()
{
lock(locker)
return sngltn?? new MySingleton();
}
}
I have written a class for my project using Singleton pattern. It is very easy to use. Hope it will work for you. Please find the code following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TEClaim.Models
{
public class LogedinUserDetails
{
public string UserID { get; set; }
public string UserRole { get; set; }
public string UserSupervisor { get; set; }
public LogedinUserDetails()
{
}
public static LogedinUserDetails Singleton()
{
LogedinUserDetails oSingleton;
if (null == System.Web.HttpContext.Current.Session["LogedinUserDetails"])
{
oSingleton = new LogedinUserDetails();
System.Web.HttpContext.Current.Session["LogedinUserDetails"] = oSingleton;
}
else
{
oSingleton = (LogedinUserDetails)System.Web.HttpContext.Current.Session["LogedinUserDetails"];
}
//Return the single instance of this class that was stored in the session
return oSingleton;
}
}
}
Now you can set variable value for the above code in your application like this..
[HttpPost]
public ActionResult Login(FormCollection collection)
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
User_Details.UserID = "12";
User_Details.UserRole = "SuperAdmin";
User_Details.UserSupervisor = "815978";
return RedirectToAction("Dashboard", "Home");
}
And you can retrieve those value like this..
public ActionResult Dashboard()
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
ViewData["UserID"] = User_Details.UserID;
ViewData["UserRole"] = User_Details.UserRole;
ViewData["UserSupervisor"] = User_Details.UserSupervisor;
return View();
}
In c# it could be (Thread safe as well as lazy initialization):
public sealed class MySingleton
{
static volatile Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton(), true);
public static MySingleton Instance => _instance.Value;
private MySingleton() { }
}