What's wrong with this singleton I created - c#

I created a class which allows access to global access to a variable while only creating it once, essentially a singleton.
However, it doesn't match any of the 'correct' ways to implement a singleton. I assume that it's not mentioned because there is something 'wrong' with it but I can't see any problem with it other then the lack of lazy initialization.
Any thoughts?
static class DefaultFields
{
private static readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
private static readonly IniConfigSource Ini = GetIni();
/// <summary>
/// Creates a reference to the ini file on startup
/// </summary>
private static IniConfigSource GetIni()
{
// Create Ini File if it does not exist
if (!File.Exists(IniPath))
{
using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
{
var iniConfig = new IniConfigSource(stream);
iniConfig.AddConfig("default");
iniConfig.Save(IniPath);
}
}
var source = new IniConfigSource(IniPath);
return source;
}
public static IConfig Get()
{
return Ini.Configs["default"];
}
public static void Remove(string key)
{
Get().Remove(key);
Ini.Save();
}
public static void Set(string key, string value)
{
Get().Set(key, value ?? "");
Ini.Save();
}
}

It doesn't follow the usual singleton patterns as your class is static and just controls access to static variables.
Where as a singleton is normally a static single instance of a class where the only static functions are that to create and access the singleton that stores variables as normal non static member variables.
Meaning the class could quite easily be changed or made to be instanced more then once but yours cannot

You are right about the singleton, its a class with a unique instance that provides global access.
It might seem like a static class but usually its implemented in a different way.
Also bear in mind that this pattern should be used with some precaution, as its really hard to refactor out a singleton once its deep in the code. Should be used primarily when you have hardware constraints or are implemented unique points of access to a factory. I would try to avoid it whenever possible.
An example of an implementation is as follows:
public class A
{
/// <summary>
/// Unique instance to access to object A
/// </summary>
public static readonly A Singleton = new A();
/// <summary>
/// private constructor so it can only be created internally.
/// </summary>
private A()
{
}
/// <summary>
/// Instance method B does B..
/// </summary>
public void B()
{
}
}
And could be used like
A.Singleton.B()
Hope that helps.

All the methods on your class are static, so you are hiding the single instance from your users. With the singleton pattern the single instance is exposed via a public property usually called Instance (in other languages like Java it might be a method called getInstance or similar).
Your code is not wrong - it's just not the singleton pattern. If you wish to implement a singleton I would recommend Jon Skeet's article Implementing the Singleton Pattern in C#.

The biggest problem I see is that you're not doing any SyncLock-ing around writes to your INI file - multiple threads that attempt to write values at the same time could end up with unpredictable results, like both making writes and only one persisting (or multiple threads attempting to write the file at once, resulting in an IO error).
I'd create a private "Locking" object of some kind and then wrap the writes to your file in a SyncLock to ensure that only one thread at a time has the ability to change values (or, at the very least, commit changes to the INI file).

I am interested in answers to this question as well. In my opinion, there is a flood of singleton examples that use lazy instantiation, but I think you have to ask yourself if it's really necessary on a case by case basis.
Although this article pertains to Java, the concepts should still apply. This provides a number of examples for different singleton implementations. http://www.shaunabram.com/singleton-implementations/
I've also seen numerous references to the book "Effective Java", Item 71 - use lazy instantiation judiciously. Basically, don't do it unless you need to.

That's not really a singleton, it's a static class.
In many ways, static classes are similar to singleton's, true. But static classes can't implement interfaces, can't inherit functionality from a base class, and you can't carry a reference to them.

Why the readonly on the Ini field?
But if you want implement the singleton pattern, it's something like this:
static DefaultFields
{
private readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
private readonly IniConfigSource Ini = GetIni();
private static DefaultFields _default;
public static DefaultFields Default
{
get { if(this._default == null){ this._default = new DefaultFields(); } return this._default; }
}
private DefaultFields()
{
}
/// <summary>
/// Creates a reference to the ini file on startup
/// </summary>
private IniConfigSource GetIni()
{
// Create Ini File if it does not exist
if (!File.Exists(IniPath))
{
using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
{
var iniConfig = new IniConfigSource(stream);
iniConfig.AddConfig("default");
iniConfig.Save(IniPath);
}
}
var source = new IniConfigSource(IniPath);
return source;
}
public IConfig Get()
{
return Ini.Configs["default"];
}
public void Remove(string key)
{
Get().Remove(key);
Ini.Save();
}
public void Set(string key, string value)
{
Get().Set(key, value ?? "");
Ini.Save();
}
}

lazy initialization is very important for a singleton class. By declaring your class to be static you implement a static class, not a singleton class.

Related

Xamarin.Forms Dependency Service non-static fields/properties

I'm using Dependency Service to get the platform specific implementation of an interface.
Let's say I have the following interface:
public interface IMyInterface
{
bool IsEnabled { get; set; }
}
And the implementing class in my Android project:
[assembly: Dependency(typeof(MyClass))]
namespace App.Droid
{
class MyClass : IMyInterface
{
public bool IsEnabled { get; set; }
}
}
At some point in the code, I set IsEnabled to true.
After that, I start a new activity that makes my app go to background:
Intent intent = new Intent();
intent.SetAction(action);
intent.SetFlags(ActivityFlags.NewTask);
MainActivity.Instance.StartActivity(intent);
When my app returns to foreground, I access the property IsEnabled and I get false instead of true. This actually happens with every single property and private field of the impementing class. Are those properties garbage collected when I leave the app for a new activity?
The only way I found to solve this issue is to make all backing fields static, but this makes a lot of overhead in the code, which might be unnecessary if I knew the reasons under this behavoiur.
Not too understanding the title of your question.
If you use the singleton pattern, you can extract the properties based on the unique instantiation object when needed.Like this:
public class Singleton
{
// Define a static variable to hold an instance of the class
private static Singleton uniqueInstance;
// Define a private constructor so that the outside world cannot create instances of the class
private Singleton()
{
}
/// <summary>
/// Define public methods to provide a global access point, and you can also define public properties to provide global access points
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
// Create if the instance of the class does not exist, otherwise return directly
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
If not, you can use Properties (https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.application.properties?view=xamarin-forms)to access the data .Like this:
private void SaveConnectionData(JSON.Connection C)
{
App.Current.Properties[Cryptography.Encryption("AccessToken")] = Cryptography.Encryption(C.Access_token);
App.Current.Properties[Cryptography.Encryption("ExpiresIn")] = Cryptography.Encryption(C.Expires_in.ToString());
App.Current.Properties[Cryptography.Encryption("TokenType")] = Cryptography.Encryption(C.Token_type);
App.Current.Properties[Cryptography.Encryption("Scope")] = Cryptography.Encryption(JsonConvert.SerializeObject(C.Scope));
App.Current.Properties[Cryptography.Encryption("RefreshToken")] = Cryptography.Encryption(C.Refresh_token);
App.Current.SavePropertiesAsync();
}
You may be involved in the use of lifecycles and notifications.Also if there is a lot of data, consider using the SQLite database to save this data .Can refer to this link here
More:In Xamarin.Android, you also can try lifecycles to show saved data.Like OnResume method to show data.

C# should Singleton contain static methods?

I am having a lot of trouble choosing between using Singleton or Static for a class that contains state variables. I wanted the class object to instantiate and exist only as one.
I know both ways can store state variables. Static Class seems easy to deal with the variables as all methods will become static, which they can access the static variables without any further work.
However, this case is different for a Singleton. I have both kinds of methods; A kind that needs to access to the Singleton's Instance variable, and other that without any access to the Instance variable, which I can mark it static.
An Example:
/// <summary>Singleton.</summary>
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton(); /// <summary>Instance.</summary>
public static Singleton Instance { get { return instance; } }
private int integer; /// <summary>Integer.</summary>
public int Integer { set { integer = value; } get { return integer; } }
/// <summary>Constructor.</summary>
private Singleton() { }
/// <summary>TestA</summary>
public void TestA(int val)
{
Integer = val;
}
/// <summary>TestB</summary>
public static int TestB(int val)
{
return Instance.Integer * val;
}
/// <summary>TestC</summary>
public static int TestC(int val)
{
return val * val;
}
}
From the example given above, there are three methods; TestA, TestB, and TestC.
TestA is a non-static instance method that has access to its property.
TestB is a static method, but accesses the Instance to get its properties.
TestC is a static method that the instance has no use.
This begs the question:
Should the Singleton contains only static methods, and access to its Instance properties and methods by going through the static Instance property? In other words, all methods are similar to TestB or TestC.
Should the Singleton contains only non-static methods, regardless whether if it needs the Instance or not? All methods similar to TestA.
Should the Singleton contains both mixed static and non-static (in this case, TestA, and TestB kind) methods? Which I believe it can get rather messy.
If not, what should I do? Should I dump the idea of Singleton, and go with all static for every classes that is to be instantiated only once?
Edit: With similar question, should Singleton even contain any Static variables/field/properties beside the Instance?
You shouldnt mix up both patterns.
If you have an Singleton pattern the only static field should be the Instance(+ the getter). All your methods and fields should be accessible through the instance. If you mix it up it will only cause confusion.
If you choose the the static class pattern don't use a secret instance inside thats the job of .NET.
If you are not sure what pattern fits best for you, have a look into this Singleton-vs-Static article. It explains the pro's and con's of both of them: https://www.dotnetperls.com/singleton-static

Singleton Alternative - is it equivalent?

I know that the standard singleton pattern is as follows:
Original
public class Singleton1
{
public static Singleton1 _Instance;
public static Singleton1 Instance
{
get
{
if (_Instance == null)
{
_Instance = new Singleton1();
}
return _Instance;
}
}
private Singleton1()
{
}
}
But it seems like this code is unnecessary. To me, you could accomplish the same thing with either of the following simple design patterns:
Version 2
public class Singleton2
{
public static readonly Singleton2 Instance = new Singleton2();
private Singleton2()
{
}
}
Version 3
public class Singleton3
{
static Singleton3()
{
}
}
To me, it seems like version 2 is the superior method of doing this because it allows you to pass in parameters (or not) yet still have a finite number of instance. My application is fairly latency/performance sensitive - do any of these patterns have a performance gain?
It would seem that while it will longer to access each one the first time because the object is being created. Also, it would seem that the original one is ever so slightly slower because it must check to see whether its backing field is null every time something else accesses it.
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()
{
}
}
Fast, clean, thread-safe.
One problem with singletons implemented as static instances is that they make testing and mocking more difficult.
See this scenario:
public void BusinessLogicMethod()
{
var initialValue = MySingleton.Instance.GetInitialValue();
var processedValue = initialValue + specialSomething + businessLogic;
MySingleton.Instance.SaveProcessedValue(processedValue);
}
Now, let's say I want to write a unit-test for this method. Ideally, I want to write a test that specifies input and output and tests only the business logic. But with a static singleton, the method's implementation is tied to the singleton's implementation. Can I set the InitialValue easily at the beginning of the test, or is it dependent on other factors/DB access/whatever?
However, if I use a non-static singleton, coupled with some dependency injection or service locator pattern, I can build my function like this:
public void BusinessLogicMethod()
{
var singleton = ServiceLocator.Resolve<MySingleton>();
var processedValue = singleton.InitialValue + specialSomething + businessLogic;
singleton.SaveProcessedValue(processedValue);
}
and my test can go like this, using vaguely Moq-like mock syntax:
public void TestBusinessLogic()
{
MySingleton fakeSingleton = new Mock<MySingleton>();
fakeSingleton.Setup(s => s.InitialValue).Returns(5);
// Register the fake in the ServiceLocator
ServiceLocator.Register<MySingleton>(fakeSingleton.Object);
// Run
MyBusinessMethod();
// Assert
fakeSingleton.Verify (s => s.SaveProcessedValue()).Called(Exactly.Once);
}
without worrying about the REAL singleton implementation.
Singleton2 is not the same as Singleton1 as the Instance is not "lazy" evaluated. In Singleton1, Instance is created only when it is accessed and from then on the same one is used. In SingleTon2, the Instance is initialized with the class and before being actually accessed.
My favourite singleton implementation is this one:
http://www.codeproject.com/Articles/14026/Generic-Singleton-Pattern-using-Reflection-in-C
Make sure your .ctor is not public, which is the most common mistake, then, it is safely/fully reusable.
(I need to have a close look at Peter Kiss' one which looks nice too)
To answer your performance question, the time it takes to check whether the private field is null is negligible. Therefore I wouldn't be worrying about how it is implemented with regards to performance here.

C# Static constructors design problem - need to specify parameter

I have a re-occurring design problem with certain classes which require one-off initialization with a parameter such as the name of an external resource such as a config file.
For example, I have a corelib project which provides application-wide logging, configuration and general helper methods. This object could use a static constructor to initialize itself but it need access to a config file which it can't find itself.
I can see a couple of solutions, but both of these don't seem quite right:
1) Use a constructor with a parameter. But then each object which requires corelib functionality should also know the name of the config file, so this has to be passed around the application. Also if I implemented corelib as a singleton I would also have to pass the config file as a parameter to the GetInstance method, which I believe is also not right.
2) Create a static property or method to pass through the config file or other external parameter.
I have sort of used the latter method and created a Load method which initializes an inner class which it passes through the config file in the constructor. Then this inner class is exposed through a public property MyCoreLib.
public static class CoreLib
{
private static MyCoreLib myCoreLib;
public static void Load(string configFile)
{
myCoreLib = new MyCoreLib(configFile);
}
public static MyCoreLib MyCoreLib
{
get { return myCoreLib; }
}
public class MyCoreLib
{
private string configFile;
public MyCoreLib(string configFile)
{
this.configFile = configFile;
}
public void DoSomething()
{
}
}
}
I'm still not happy though. The inner class is not initialized until you call the load method, so that needs to be considered anywhere the MyCoreLib is accessed. Also there is nothing to stop someone calling the load method again.
Any other patterns or ideas how to accomplish this?
You need a common location to store this. You could use the app.config even if this is a seperate assembly by defining a config section in the library assembly and referencing it you proceess app.config. Or you could just add a generic setting to appSettings and reference that without using strongly typed settings. If the value is user entered then you could use isolated storage.
Finally you could put it in a well known location in the registry at install time.
For code the following is encapsulted better
public interface ICoreLib
{
void SomeMethod();
}
public static class CoreLibManager
{
private static ICoreLib coreLib;
private static volatile bool initialized;
private static readonly object lockObject = new object();
public static ICoreLib CoreLib
{
get
{
Inititialize();
return coreLib;
}
}
/// <summary>
/// The inititialize.
/// </summary>
private static void Inititialize()
{
if (initialized)
{
lock (lockObject)
{
if (!initialized)
{
string configFile = // Fech from common location
coreLib = new MyCoreLib(configFile);
initialized = true;
}
}
}
}
/// <summary>
/// The my core lib.
/// </summary>
private class MyCoreLib : ICoreLib
{
public MyCoreLib(string configPath)
{
}
public void SomeMethod()
{
}
}
}
When you have global state like this that you need to initialize and it requires outside input to complete initialization (such as a config file), then you're stuck with the outside code that knows about the input having to call Load or Initialize to initialize your global state. There's no way around this.
The issue that you've correctly observed, however, is that anybody could try to use the global state before it has been properly Initialized, which is the downside to having it exposed in this way. The way you get around this is by refactoring all of the stateful parts of your global library into an instance class and passing references to that instance through your application. Because you control when it is created and initialized, you can now ensure it has valid state before you pass it along. You trade off the convenience of global state for the better insulation you're after.
You can use the .net configuration system to do this. The simplest way to do this is to use the <appsettings> element in your web.config file, or in your appname.exe.config file. Use:
ConfigurationManager.AppSettings["property_name"]
to access a property. Whether your code is running in a web context or as a windows app, the configuration system will find the config file and load the values you need.
You can also build a more complex system with type-safe config values and hierarchical data, but my needs were pretty simple, so I didn't explore this after the first headache set in :)
You could make the class a singleton, thus ensuring there's only ever one instance of it while also allowing for the constructor parameter.
There won't be much alternatives.
Either you pass stuff around (in that case I'd not pass the string around but create a concrete (non-static) CoreLib and pass that around or you do what you suggested.
Don't forget to hide the constructor for MyCoreLib. Currently it is public which is likely unintended.
OK, thanks everyone for your assistance. I've refactored the CoreLib project and broken out the config handling into a separate project. Now we have a solution-wide shared class for config management. The class can take care of itself with a user setting, which is exposed via the static property ConfigFile. This property also persists the modified file location if the user changes via some config dialog. Also the initialized flag will be reset if the config file changes.
public interface IConfig
{
void SomeMethod();
}
public static class ConfigurationManager
{
private static IConfig config;
private static volatile bool initialized;
private static readonly object lockObject = new object();
public static string ConfigFile
{
get { return Properties.Settings.Default.ConfigFile; }
set
{
if (Properties.Settings.Default.ConfigFile == value) return;
lock (lockObject)
{
Properties.Settings.Default.Save();
initialized = false;
}
}
}
public static IConfig Config
{
get
{
Inititialize();
return config;
}
}
private static void Inititialize()
{
lock (lockObject)
{
if (initialized) return;
config = new Configuration(Properties.Settings.Default.ConfigFile);
initialized = true;
}
}
}
internal class Configuration : IConfig
{
public ClientConfig(string configFile)
{
// Parse & validate config file
}
public void SomeMethod()
{
}
}
So now in the start-up we first validate the persisted ConfigFile setting, then attempt to access the Configuration instance via the manager's Config property. Any parsing exceptions can be handled here and dealt with accordingly. Then it is up to the developer to handle any exceptions for IConfig's methods.
if (!System.IO.File.Exists(ConfigurationManager.ConfigFile))
{
// Display config file locator dialog
ConfigurationManager.ConfigFile = someDialog.FileName;
}
try
{
IConfig config = ConfigurationManager.Config;
}
catch
{
// Error parsing config file
}

How to implement a singleton in C#?

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() { }
}

Categories