Is this Lazy<T> considered a singleton? - c#

I need to be able to call this method
IDatabase cache = CacheConnectionHelper.Connection.GetDatabase();
From anywhere on my application, I got this connection helper class from some azure page
public class CacheConnectionHelper
{
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
return ConnectionMultiplexer.Connect(SettingsHelper.AzureRedisCache);
});
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
}
The question is:
Is the above singleton and if not how should I change it, so that each time that I try get a Connection, its only using one instance and doesnt try to open more than one connection

Yes, that's a singleton because Lazy<T> makes sure that your factory delegate
return ConnectionMultiplexer.Connect(SettingsHelper.AzureRedisCache);
...is only invoked once. It will be invoked the first time lazyConnection.Value is read. Remaining invocations will return the same value/instance that was returned from the first invocation (it is cached).
For clarity, I would make CacheConnectionHelper static:
public static class CacheConnectionHelper
By the way, it looks like your code is copied from this MSDN article.
This provides a thread-safe way to initialize only a single connected ConnectionMultiplexer instance.

Correct, it is singleton.
Reference : using .NET 4's Lazy type
If you're using .NET 4 (or higher), you can use the System.Lazy
type to make the laziness really simple. All you need to do is pass a
delegate to the constructor which calls the Singleton constructor -
which is done most easily with a lambda expression.
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()
{
}
}
It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.

Related

Do two instances of a singleton class have the same property value?

I am new to design patterns in C#. Can anyone please give me some instructions about the implementation of a Singleton class. I just implemented a tutorial but I am not able to understand use of singleton class with this "singleton means we can create only one instance of a class". Then why we don't access property which is written in the singleton class using two different instance of the class.
Please look at my code and give me instructions about the mistake I made.
static void Main(string[] args)
{
Singleton instance = Singleton.getInstance();
instance.Message = "Text Message";
Singleton instance1 = Singleton.getInstance();
Console.WriteLine(instance.Message);
Console.WriteLine(instance1.Message);
Console.ReadKey();
}
class Singleton
{
private static Singleton singleton=null;
private Singleton(){}
public static Singleton getInstance()
{
if (singleton!=null)
{
return singleton;
}
return new Singleton();
}
public string Message{get; set;}
}
Your singleton is incorrect.
More correct version:
class Singleton
{
private static Singleton singleton = null;
private Singleton(){}
public static Singleton getInstance()
{
if (singleton!=null)
{
return singleton;
}
return (singleton = new Singleton()); //here is
}
public string Message{get; set;}
}
And very good solution:
class Singleton
{
private static Lazy<Singleton> singleton = new Lazy<Singleton>(()=> new Singleton());
private Singleton() { }
public static Singleton getInstance()
{
return singleton.Value;
}
public string Message { get; set; }
}
It has no problems with thread-safity and lazy initialization.
By default, all public and protected members of the Lazy class are
thread safe and may be used concurrently from multiple threads. These
thread-safety guarantees may be removed optionally and per instance,
using parameters to the type's constructors.
Your Singleton implementation is incorrect.
A Singleton is designed to only allow none or a single instance at all times.
This is where you went wrong:
public static Singleton getInstance()
{
// "singleton" will always be null.
if (singleton != null)
{
return singleton;
}
// Always returns new instance rather than existing one.
return new Singleton();
}
To fix it you should write:
public static Singleton getInstance()
{
// Return the instance we might have stored earlier.
if (singleton != null)
return singleton;
// Now we store the only instance that will ever be created.
singleton = new Singleton();
return singleton;
}
Note that this is not thread safe if called multiple times in parallel.
As a resource I can recommend Jon Skeet's post:
http://csharpindepth.com/Articles/General/Singleton.aspx
He explaines six different solutions (including thread-safety and the Lazy(T)) to the Singleton Pattern and how to code them.
Does two instance of singleton class has a same property value?
The answer to your question is yes, they has the same property value.
Important thing is understand why, and the reason is the core of what a singleton is. So, why?:
Because you are confusing two references with two instance.
There are no two instances, there are always one none or one instance of the singleton class.
In your code, singleton variable and singleton1 variable are pointing both to the same object, the singleton, and the reason is because of the implementation of the method getInstance(), is simple to understand :
If method is called for the very first time, then it creates for unique time the singleton object with method new.
If method is called after a first time, it will return the singleton object created in the first call of method.
So, no matter how many variables of type Singleton you have, you will always have only one Singleton created with the new method, the instance, the singleton instance.

When using a singleton pattern, should my public class return the private or public instance?

I have a singleton defined like this:
public partial class MoonDataManager
{
static MoonDataManager _singletonInstance;
public static MoonDataManager SingletonInstance
{
get
{
return _singletonInstance;
}
private set
{
_singletonInstance = value;
}
}
I have a function that safely creates the instance:
public static async Task<MoonDataManager> CreateSingletonAsync()
{
_singletonInstance = new MoonDataManager();
Should I:
return _singletonInstance; (field)
or
return SingletonInstance; (property)
I'm concerned with Garbage Collection, especially in iOS or Android within Xamarin.
Also if there are naming patterns for this in C# let me know if I deviated from a standard.
Update:
Now I think I really got myself stuck with threading and async methods. Here are the objects and their goals:
MoonDataManager : Run the RegisterTable<Models.IssuerKey> once per table. This is a generic method that essentially runs (new MobileServiceSQLiteStore).DefineTable<T>()
OfflineStore : This is a MobileServiceSQLiteStore.
MobileClient : This is a MobileServiceClient.
MoonDataManager Dependencies: The MoonDataManager requires OfflineStore and MobileClient to finish initialization. Specifically, it does a MobileServiceClient.SyncContext.InitializeAsync(OfflineStore)
I'm not sure how to make sense of this spaghetti of dependencies... or how to make the code look nice, and be thread safe.
Here is the new iteration of the code:
private readonly Lazy<MobileServiceClient> lazyMobileClient =
new Lazy<MobileServiceClient>(() => new MobileServiceClient(Constants.ApplicationURL), true); // true for thread safety
public MobileServiceClient MobileClient { get { return lazyMobileClient.Value; } }
private readonly Lazy< MobileServiceSQLiteStore> offlineDB =
new Lazy<MobileServiceSQLiteStore>(() => new MobileServiceSQLiteStore(Constants.OfflineDBName), true ); // true for thread safety
private MobileServiceSQLiteStore OfflineStore { get { return offlineDB.Value; } }
private static readonly Lazy<MoonDataManager> lazy = new Lazy<MoonDataManager>(() => new MoonDataManager(), true); // true for thread safety
public static MoonDataManager Instance { get { return lazy.Value; } }
private MoonDataManager()
{
MoonDataManager.Instance.RegisterTable<Models.IssuerKey>();
// Initialize file sync
// todo: investigate FileSyncTriggerFactory overload.
//Was present on Mar 30, 2016 Channel9 https://channel9.msdn.com/events/Build/2016/P408
MoonDataManager.Instance.MobileClient.InitializeFileSyncContext
(new IssuerKeyFileSyncHandler(Instance), Instance.OfflineStore);
// NOTE THE ASYNC METHOD HERE (won't compile)
await MoonDataManager.Instance.MobileClient
.SyncContext.InitializeAsync(MoonDataManager.Instance.OfflineStore,
StoreTrackingOptions.NotifyLocalAndServerOperations);
}
For .NET 4 or higher, you can use the Lazy<T> and create it like this.
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton(), true); // true for thread safety
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
It will be created only if it is accessed and only the first time and it is threadsafe.
The definition
static MoonDataManager _singletonInstance;
ensures that the instance of MoonDataManager is a GC root, and it will not be collected until the application domain ends, because it is a static value.
I'd return the private singleton and forego the auto property that you have.
public partial class MoonDataManager
{
private static readonly Lazy<MoonDataManager> _manager =
new Lazy<MoonDataManager>(() => new MoonDataManager());
public static MoonDataManager SingletonInstance => _manager.Value;
}
When MoonDataManager.Value is accessed for the first time, it is initialized using the Func<MoonDataManager> that was passed to the constructor for Lazy<T>. On subsequent accesses, the same instance is returned.
A Singleton creates itself the first time it's accessed, in a way that ensures only one instance will get created, even if a second thread tries to access it while it's still being instantiated
your CreateSingletonAsync() violates this, and looks like it'd allow for multi-thread nastiness
You want something like:
public static MoonDataManager SingletonInstance
{
get
{
if (_singletonInsatnce != null)
return _singletonInstance;
lock (lockobject)
{
// check for null again, as new one may have been created while a thread was waiting on the lock
if (_singletonInsatnce != null)
return _singletonInstance;
else
// create new one here.
}
}
// no setter, because by definition no other class can instantiate the singleton
}
All this is just to ensure that two threads asking for one object don't end up creating two objects, or the second thread getting a half-created object if the first thread's one is still being created.
NB: Singletons have become unfashionable.
NB: If you can be sure that you've got time to create your object before it's ever accessed, you can just use a static member and create it on application start.
Your question "should I return the property or field" doesn't make sense -- you're already returning the field from the property getter, which is standard practise. Where else are you wanting to return something?
You should return the private instance. You can read more about the singleton pattern on MSDN. The standard singleton implementation is as follows:
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Although, normally, you don't have a setter for the property. This pattern has already previously been discussed on SO.

c# Singleton Pattern vs Static Property

When I tried to use 2 different versions of the same class , they act actually the same.
I searched but can't find a satisfied answer for this question
What are the differences between Singleton and static property below 2 example, it is about initialization time ? and how can i observe differences ?
Edit : I don't ask about differences static class and singleton. Both of them non static, only difference is, first one initialized in Instance property, second one initialized directly
public sealed class Singleton
{
private static Singleton instance;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
public sealed class Singleton2
{
private static Singleton2 instance = new Singleton2();
private Singleton2()
{
}
public static Singleton2 Instance
{
get
{
return instance;
}
}
}
Your first singleton implementation isn't thread safe; if multiple threads try to create a singleton at the same time it's possible for two instances to end up being created. Your second implementation doesn't have that flaw.
Other than that, they're functionally the same.
The instance of the Singleton class will be created the first time it is requested by the Singleton.Instance method.
The instance of Singleton2 will be created on initialization of its type which can be caused by several mechanisms. It will certainly be created before accessing any property or method on the Singleton2 class

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.

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