How do I use this singleton example - c#

This page does a good job of describing how to create c# singletons, but it doesn't seem to explain how you actually use them.
http://msdn.microsoft.com/en-us/library/ff650316.aspx
So if I were to create this singleton below, how do I kick things off (I don't think I can instantiate it directly) and if I don't have an instance object how to I access it - e.g. how do I read and write to property prop1
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
public int prop1 {get; set;}
}

To use a singleton class, you simply call it's public static instance property. For example, suppose that you have a logger, and you don't want other developers to always instantiating it:
public class Logger
{
private static Logger logger = new Logger();
private Logger() { }
public static Logger Instance
{
get
{
return logger;
}
}
public void Log(text)
{
// Logging text
}
public int Mode { get; set; }
}
You should log this way:
Logger.Instance.Log("some text here");
In your case, to read/write Mode property, you should write:
Logger.Instance.Mode = 1;
int mode = Logger.Instance.Mode;

You can access the instance by using
Singleton.Instance

You only create the instance once, So you will have something like this
public sealed class Singleton
{
private static readonly Singleton instance;
private bool initialised = false;
private Singleton(){}
public static Singleton Instance
{
get
{
if(initialised)
return instance;
else {
initialsed = true;
instance = new Singleton();
return instance;
}
}
}
public int prop1 {get; set;}
}

Singleton.Instance.prop1 = 12;

Related

What wrong with that singleton implementation

I wrote static singleton and add class inside the Singleton class.
However, it seem like it broke the pattern.
any advice why?
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public int MyProperty { get; set; } = 10;
static Singleton() { }
private Singleton() { }
public static Singleton Instance {get { return instance; } }
public class SecondSingleton
{
public Singleton secondInstance;
public SecondSingleton()
{
secondInstance = new Singleton();
secondInstance.MyProperty = 20;
}
}
}
class Program
{
static void Main(string[] args)
{
Singleton s1 = Singleton.Instance;
Singleton.SecondSingleton s2 = new Singleton.SecondSingleton();
Console.WriteLine($"s1.MyProperty = {s1.MyProperty}");
Console.WriteLine($"s2.MyProperty = {s2.secondInstance.MyProperty}");
Console.ReadLine();
}
}
Asper WIKI : Singleton restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system.
The moment you say "SecondInstance", then it is broke the pattern.
You are creating new Singleton in SecondSingleton constructor, which means secondInstance != Singleton.Instance. Instead, you should get the Instance, i.e: secondInstance = Singleton.Instance;

How to define a global variable in a busy ASP.NET MVC

In my site, I call a third party API. To avoid hitting its rate limit, I need to define a global variable to enqueue requests. (I'm using RateLimiter any better solution?)
namespace MySite.App_Start
{
public static class Global
{
public static int MaxCount { get; set; } = 30;
public static TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(1);
private static TimeLimiter rateLimiter;
public static TimeLimiter RateLimiter
{
get
{
if (rateLimiter == null)
rateLimiter = TimeLimiter.GetFromMaxCountByInterval(MaxCount, Interval);
return rateLimiter;
}
}
}
}
Then I'll use RateLimiter property. But I've read a lot that having a global variable is not a good idea. Considering my site has a lot of requests per second, is my code safe to use? Thanks.
Your code isn't 100% safe since it could create multiple instances of TimeLimiter in the beginning and depending on surrounding code, it could be a problem. I'm guessing it wouldn't be a big problem, but it's better to write the code properly to begin with.
This is something an IoC container handles nicely, but if you don't want to use one, you could use Lazy:
private static TimeLimiter rateLimiter = new Lazy(() =>
TimeLimiter.GetFromMaxCountByInterval(MaxCount, Interval));
public static TimeLimiter RateLimiter => rateLimiter.Value;
Maybe, you can make it thread-safe by using lock statement.
public static class Global
{
public static int MaxCount { get; set; } = 30;
public static TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(1);
private static object _lockObject = new object();
private static TimeLimiter rateLimiter;
public static TimeLimiter RateLimiter
{
get
{
lock (_lockObject)
{
if (rateLimiter == null)
rateLimiter = TimeLimiter.GetFromMaxCountByInterval(MaxCount, Interval);
return rateLimiter;
}
}
}
}
Your code is not thread-safety.
Try this:
public class Singleton
{
protected Singleton() { }
private sealed class SingletonCreator
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
}
public static Singleton Instance
{
get { return SingletonCreator.Instance; }
}
}
Or use your favorite IoC-container with creating SingleInstance object

How to initialize a static property before initializing a static class?

Below Class2 has a property that needs to be set before GetSomething is called, however because I access Class2 at the top of Class1 the property is always null when it gets to Something class. I can't seem to figure out how to change my code to set the property before it's used. Anyone?
EDIT
I want to pass the dependency from form1's constructor, not hardcode it further up the chain.
public partial class form1
{
private static readonly ISomeConstructedClass someConstructedClass = Class1.SomeConstructedClass;
public form1()
{
someConstructedClass.SomeDependency = new SomeDependency();
someConstructedClass.Whatever();
}
}
public static class Class1
{
public static readonly ISomething something = (ISomething)Class2.GetSomething("something");
public static ISomeConstructedClass SomeConstructedClass
{
get
{
return something.SomeConstructedClass;
}
}
}
....
}
public class Class2
{
public static ISomeDependency SomeDependency
{
get;
set;
}
public static GetSomething(string something)
{
switch(something)
{
case "something":
return new Something( SomeDependency );
}
}
}
public class Something : ISomething
{
public ISomeDependency SomeDependency
{
get;
set;
}
public Something(ISomeDependency someDependency)
{
SomeDependency = someDependency;
}
}
[Re]Edit:
I was confused about what you were trying to do before, you just need to create the dependency first.
public partial class form1
{
private static /*readonly*/ ISomeConstructedClass someConstructedClass;
public form1()
{
Class2.SomeDependency = new SomeDependency();
someConstructedClass = Class1.SomeConstructedClass;
someConstructedClass.Whatever();
}
}
I would also move the creation of something into the property just to make sure it is not initialized too soon (before the form1 constructor is called).
public static class Class1
{
public static ISomething something;
public static ISomeConstructedClass SomeConstructedClass
{
get
{
if (something == null) {
something = (ISomething)Class2.GetSomething("something");
}
return something.SomeConstructedClass;
}
}
}
You can use a static constructor. This is called before any static (or instance for that matter) fields or methods are called/accessed.
Something like:
static Class2() {
SomeDependency = SomeDependencyYouNeed;
}
Why are you using static methods? It looks like you're attempting a sort of Dependency Injection. Either create an instance of Class2 and pass the dependency in the constructor (and don't use static methods), or pass the dependency as a parameter of the GetSomething() method.
public static GetSomething(string something, ISomeDependency dependency).

Thread safety of C# singleton instance in ApplicationState

I have a bit of code that I've been trying to examine for thread safety. I'm using the basic lazy singleton model found here. I was wondering if it is still thread safe if I'm putting the instance in the HttpApplicationState object. I need to access this instance across all instances of the web application, so if this is not thread safe how can I make it thread safe?
public sealed class EmailWorker {
private HttpApplicationState _app;
private const EMAIL_WORKER = "EmailWorker";
EmailWorker() { }
class NestedWorker {
static NestedWorker() { }
internal static readonly EmailWorker Instance = new EmailWorker();
}
public static void Initialize(HttpApplicationState appState) {
_appState = appState;
_appState.Lock();
if (_appState[EMAIL_WORKER] == null) {
_appState.Add(EMAIL_WORKER, NestedWorker.Instance);
}
_appState.UnLock();
}
public static EmailWorker Instance {
get {
// TODO: If we haven't called Initialize() first then throw exception
return (EmailWorker)_appState[EMAIL_WORKER];
}
}
}
You don't need to use Application state at all.
It should be thread-safe, but why bother?
A "standard" singleton will also be accessible across the entire application, and it won't require injecting and keeping a reference to the HttpApplicationState:
public sealed class EmailWorker
{
private EmailWorker() { }
private static class NestedWorker
{
static NestedWorker() { }
internal static readonly EmailWorker Instance = new EmailWorker();
}
public static EmailWorker Instance
{
get { return NestedWorker.Instance; }
}
}

How can I make one class solely responsible for creating and providing access to another class

This is how I understand I can implement the singleton pattern in C#:
public class ChesneyHawkes{
private static ChesneyHawkes _instance = new ChesneyHawkes();
public ChesneyHawkes Instance {get{return _instance;}}
private ChesneyHawkes()
{
}
}
What if I want to provide a single instance of an object, so that there can only ever be one, make the access to it public, but only allow it to be created or replaced by another singleton.
// The PuppetMaster should be the only class that
// can create the only existing Puppet instance.
public class PuppetMaster{
private static PuppetMaster_instance = new PuppetMaster();
public static PuppetMaster Instance {get{return _instance;}}
// Like a singleton but can be replaced at the whim of PuppetMaster.Instance
public static Puppet PuppetInstance {get {return Puppet;}}
private PuppetMaster()
{
}
public class Puppet{
// Please excuse the pseudo-access-modifier
puppetmasteronly Puppet(){
}
}
}
// To be accessed like so.
PuppetMaster.Puppet puppet = PuppetMaster.Instance.PuppetInstance;
You don't really need more than one singleton for that. Look at this example:
using System;
// interface for the "inner singleton"
interface IPuppet {
void DoSomething();
}
class MasterOfPuppets {
// private class: only MasterOfPuppets can create
private class PuppetImpl : IPuppet {
public void DoSomething() {
}
}
static MasterOfPuppets _instance = new MasterOfPuppets();
public static MasterOfPuppets Instance {
get { return _instance; }
}
// private set accessor: only MasterOfPuppets can replace instance
public IPuppet Puppet {
get;
private set;
}
}
class Program {
public static void Main(params string[] args) {
// access singleton and then inner instance
MasterOfPuppets.Instance.Puppet.DoSomething();
}
}

Categories

Resources