Correct Usage of the Singleton Pattern - c#

I have a requirement where only one instance of BillLines is ever created, which is of course perfect for the singleton pattern.
Looking at Jon's Skeet's post I'm not quite understanding where I create my 'new' object (i.e. the useful object not some abstract Singleton object).
Does this appear correct to you?
public sealed class ContextSingleton
{
private static readonly Lazy<ContextSingleton> Lazy =
new Lazy<ContextSingleton>(() => new ContextSingleton());
public static ContextSingleton Instance { get { return Lazy.Value; } }
private ContextSingleton()
{
}
//Is this correct? Where should I 'new' this?
public readonly IBillLineEntities Context = new BillLines.BillLines();
}
Being accessed like this:
var contextSingleton = ContextSingleton.Instance.Context;
Update
I don't have access to the internals of BillLines but I need to ensure only one instance of it exists.

I assume BillLines should be your Instance variable.
It should look like this:
public static class ContextSingleton
{
private static readonly Lazy<BillLines> _instance =
new Lazy<BillLines>(() => new BillLines());
public static BillLines Instance { get { return _instance.Value; } }
private ContextSingleton()
{
}
}
And you use it like this:
ContextSingleton.Instance
Edit
This answer was targeting the creation of a singleton about a specific class. If other people have access to your BillLines class and can create their own instance of it, then you should probably rethink what you're trying to do. If you do control the exposure of your BillLines class, you should make it so it is only exposed in the internal implementation of the singleton you're exposing, so no other person can create a new BillLines as they see fit.

Something simple like this?
public class BillLines
{
private BillLines()
{
}
private static BillLines _billLines = null;
public static BillLines Instance
{
get
{
if (_billLines == null)
_billLines = new BillLines();
return _billLines;
}
}
}

Thanks to the comments from #JonSkeet and #RobH I went down the dependency injection route. I picked Ninject and this does the job as I expected:
public class NinjectBindings : NinjectModule
{
public override void Load()
{
Bind<IBillLineEntities>.To<BillLines.BillLines>().InSingletonScope();
}
}

Related

How to access classes with on one instance?

I have multiple classes in the service layer of my app.
Let's say I need to access some method from AbcService.cs in my controller. Then, I need to access some method from XyzService.cs in the same controller. Then another.......For this, I would need to create an object of each Service class separately in the constructor. Also, if I needed to access these methods in another cntroller I would again have to create objects of AbcService, XyzService, etc. I want to have one instance that can give me access to methods of all service classes.
Something like:
generalService.AbcService.MethodName();
generalService.AbcService.MethodName();
How do I do this in the best possible way?
You can use inheritance and create a class that (eventually) inherits from all of them, thus inheriting their methods. Or you can make them inherit from each other (this way you'll have to use the service class that inherits from both, as it would have all the methods that can be inherited).
To put it very simply, it can go like this using inheritance (I assume the service classes were not inheriting from anything until now):
public class ServiceClassA
{
//Certain Methods
}
public class ServiceClassB : ServiceClassA
{
//Other methods, this class also has ServiceClassA methods
}
public class ServiceClassC : ServiceClassB
{
//Even more methods, this class also has ServiceClassA and ServiceClassB methods
}
//... and so on
Assuming the lowest class in the inheritance tree is ServiceClassC for example, you only need a ServiceClassC object and you'll be able to access the needed (inherited) methods.
Create service layer so that other componentns can access easily.
public class Program
{
static void Main(string[] args)
{
Global.ServiceABC.MethodA();
Global.ServiceXYZ.MethodB();
}
}
public class Global
{
private static ABC serviceABC;
public static ABC ServiceABC { get
{
if (serviceABC == null)
{
serviceABC = new ABC();
}
return serviceABC;
}
}
private static XYZ serviceXYZ;
public static XYZ ServiceXYZ
{
get
{
if (serviceXYZ == null)
{
serviceXYZ = new XYZ();
}
return serviceXYZ;
}
}
}
public class ABC
{
public void MethodA() { }
}
public class XYZ
{
public void MethodB() { }
}
Unfortunately in C# you can NOT inherit from two classes at once so something like
public class CombinedService : AbcService, XyzService {
}
is not possible.
You can however use static methods to have only one instance per service like this:
public static class ServiceManager {
// The variable holding the instance
private static AbcService _abcService = null;
// Access to the instance and single instance creator
public static AbcService AbcServiceInstance {
get {
if (_abcService == null) {
// Create your Instance here
_abcService = new AbcService();
}
return _abcService;
}
}
// The variable holding the instance
private static XyzService _xyzService = null;
// Access to the instance and single instance creator
public static XyzService XyzServiceInstance {
get {
if (_xyzService == null) {
// Create your Instance here
_xyzService = new XyzService();
}
return _xyzService;
}
}
}
Because they are static you can access them from everywhere in the code just by calling the static class properties like this:
ServiceManager.AbcServiceInstance.SomeMethod();
ServiceManager.XyzServiceInstance.SomeMethod();
You can also shorten the instantiation and accessor like this:
private static AbcService _abcService = new AbcService();
public static XyzService XyzServiceInstance {
get { return _abcService; }
}
If the instances can just be created like this and don't need any more parameters or configuration.
You should consider using a dependency injection container like Autofac. Register your service classes as Single Instance scope. You will get only one instance of a service class whenever you request it in every individual controller and even you do not need to create instance of it on your own.All is done by Ioc Container.
var builder = new ContainerBuilder();
builder.RegisterType<SomeService>().SingleInstance();
It somewhat depends how you choose to implement your services, but generally speaking you want some layer that encapsulate your services which is a singleton or that you inject\produce a single instance of it.
Encapsulation:
First try to look at a facade design pattern.
http://www.dofactory.com/net/facade-design-pattern
And btw if you don't need something complex and don't mind have an extra level of indirection then you can have some version of the facade like
KindOfSimpleFacade
{
public IServiceA ServiceA { get; }
public IServiceB ServiceB { get; }
}
Regarding the singleton there are a few ways to get it:
inject the facade object to the (just provide the same instance to each one of the controllers as an input).
(Facade) Factory -http://tutorialspoint.com/design_pattern/factory_pattern.htm
The factory will produce a single instance of the facade.
use static members inside the facade for example:
public class KindOfSimpleFacade
{
private static readonly serviceA = new ServiceA();
private static readonly serviceB = new ServiceB();
public IServiceA ServiceA { get { return serviceA; } }
public IServiceB ServiceB { get { return serviceB; } }
}

Static constructor - Singleton Design pattern in c#

What if, I replaced private constructor with a static constructor in singleton Design pattern?
public sealed class Singleton
{
private static Singleton instance=null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
Static constructor will be called only once and I couldn't find any difference in the implementation. Can we replace private with static constructor?
All that the private constructor is really doing in this case is preventing anything outside of the class from instantiating an instance of class Singleton, which is almost certainly intentional as a singleton should only have a single instance.
Static class constructors are run once for a type, at an unknown time, before the type, or any of it's static members, is to be utilized. Static fields are initialized before the static constructor would be run.
So, I suppose you could replace the constructor with a static one, but that would then give you the implicit parameter-less constructor on the Singleton Type, which would allow anyone to instantiate an instance, which is likely at odds with why you are using the singleton pattern in the first place. It also wouldn't change anything about how your class was being constructed, really, so why do it?
Take the following class as an example:
public class Test { }
Under the covers, because there is no declared constructor, the C# compiler implicitly adds a parameterless, public constructor to the class, allowing consumers to create an instance.
public class Program {
public static void Main() {
var test = new Test();
}
}
This is all fine and good if you want to be able to make instances of your class. The singleton pattern intends to only provide a single instance of a type to the consumers. We could add this static instance to our test type like so:
public class Test { public static Test Instance {get;} = new Test(); }
and we would be able to get this static instance like so:
public class Program {
public static void Main() {
var test = Test.Instance; // good
var other = new Test(); // less than ideal
}
}
So we are providing access to our singleton object through it's instance field, as expected, but we can still create instances of the singleton type, which is less good, as it goes against the purpose of a singleton (namely, having only a single shared instance.)
So we add a private, parameterless constructor to the type.
public class Test {
private Test() {}
public static Test Instance {get;} = new Test();
}
Adding a constructor to a type will cause the C# compiler not to add an implicit public parameter-less constructor. Making it private allows it to be accessed within the class scope, which is used for instantiating our instance property, and prevents anything else from instantiating the object. The end result being:
public class Program {
public static void Main() {
var test = Test.Instance; // good
var other = new Test(); // Compile time error
}
}
Your singleton object now prevents other instances of the class from being instantiated, and the only way to use it is through the instance property as intended.
In simple terms, if you remove the private constructor, then anyone will be able to create a new instance of Singleton:
// With the private constructor, the compiler will prevent this code from working.
// Without it, the code becomes legal.
var newInstance = new Singleton();
And if anyone can instantiate Singleton as above, then you no longer have a singleton.
Another cleaner way to do it is to use readonly on you private instance.
This is less code and also thread safe. The CLR takes care of everything for you, no need for lock , check for null and stuff.
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
public static Singleton Instance {
get {
return _instance;
}
}
private Singleton()
{
}
}
Then simply test:
[TestMethod]
public void IsSingleton()
{
Assert.AreSame(Singleton.Instance, Singleton.Instance);
}
EDIT:
example using lock
public sealed class Singleton
{
private static readonly object _lock = new object();
private static Singleton instance = new Singleton();
public static Singleton Instance
{
get
{
lock(_lock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
private Singleton()
{
}
}
In simplest terms, if you remove private, the default public constructor will get exposed. Then outsiders will be allowed to use new Singleton(); and make number of instances of Singleton class. So no Singleton Pattern will be there.
Additionally this classic implementation of Singleton pattern (private constructor + static getInstance() with either lazy-loading or eager loading) is so evil. In modern day you must switch to a Dependency-Injection framework instead.
This should work just fine. You could also make the class static and generic so you can store whatever kind of value in instance you want it to hold. This would facilitate the separation of concerns, keeping the singleton pattern and the class that it will contain separate.

Singleton Inheritance C#

I was trying to implement a singleton inheritance for my log system, so I would be able to separate the system events from user behavior. I found this nice post in Java. Despite the Generics difference I could implemente this attached first version (non thread safe for a while).
public abstract class Log
{
private static volatile Dictionary<Type, Log> instances = new Dictionary<Type, Log>();
public static Log GetInstance(Type type) {
Log instance = null;
if (!Log.instances.ContainsKey(type))
{
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Default,
null,
new Type[0],
new ParameterModifier[0]);
instance = ctor.Invoke(new object[0]) as Log;
instances.Add(type, instance);
}
else
{
instance = Log.instances[type];
}
return instance;
}
private Log() { }
public class UserLog : Log
{
private UserLog() : base() { }
}
public class SystemLog : Log
{
private SystemLog() : base() { }
}
}
The highlight line above shows the attempt to create a new instance. But is doesn't work and returns a null instance of ConstructorInfo.
1) Any ideia about how to use the GetConstructor method? I know it has 3 overloaded versions, but the first one is only for public constructors. If I change the visibility of the constructor to public I can use other overloaded version (this one), but this specific version I can't even with public constructors.
2) In C#, is it possible to call a private constructor from other class like I'm trying to do? I have implemented it in Java, but in C# it might be different.
Since your binding flags don't specify Private, you won't get your private constructors. If there were public, you'd need to specify Public.
That said, I don't understand your desire to implement this in this way. It seems like a lot of extra work for no good reason.
I would do it like this:
public abstract class Log
{
public class UserLog : Log
{
private static readonly Lazy<UserLog> _instance =
new Lazy<UserLog>(() => new UserLog());
public static UserLog Instance { get { return _instance.Value; } }
}
public class SystemLog : Log
{
private static readonly Lazy<SystemLog > _instance =
new Lazy<SystemLog >(() => new SystemLog ());
public static SystemLog Instance { get { return _instance.Value; } }
}
}
I.e. just follow the normal singleton idiom for each of the actual singleton classes.
If you specify that the generic type will have to inherit from Log, and that it will have the new(), you can get away with using the parameterless constructor. You also would have to change your constructor to protected so that the child class can call it:
public abstract class Log
{
private static volatile Dictionary<Type, Log> instances = new Dictionary<Type, Log>();
public static TLogType GetInstance<TLogType>() where TLogType : Log, new()
{
TLogType instance = null;
var type = typeof(TLogType);
if (!Log.instances.ContainsKey(type))
{
instance = new TLogType();
instances.Add(type, instance);
}
else
{
instance = (TLogType)Log.instances[type];
}
return instance;
}
protected Log() { }
}
I don't think you can call the private constructors outside the class (they are private, after all), but through reflection there may be something that can be done (I'm no reflection expert). Using protected instead of private may get you the results you want.

A Singleton should be inheritable or not?

A Singleton should be inheritable or They should not be ?
According to Gof "when the sole instance should be extensible by subclassing, and clients
should be able to use an extended instance without modifying their code."
but then why do i see Sealed and Private constructor examples on MSDN
In my projects, I use an Ambient Context implementation from Mark Seemanns book Dependency Injection in .NET. The main point of use of that pattern is that always when you are asking for Current instance, there has to be something and also Context can be switched by other implementation.
F.E.
public class TimeContext
{
private static TimeContext _instance;
public static TimeContext Current
{
get
{
if (_instance == null)
{
_instance = new DefaultContext();
}
return _instance;
}
set
{
if (value != null)
{
_instance = value;
}
}
}
public abstract DateTime GetDateTime();
}
And concrete implementation of context should be like:
public class DefaultContext : TimeContext
{
public DateTime GetDateTime()
{
return DateTime.Now();
}
}
I think you're mixing two different things here. The singleton pattern calls for a single instance that is used by all callers. Inheritance just means I can share common logic between a class hierarchy. This, I feel, is an implementation of the singleton pattern:
(ignore the lack of locking/thread safety, for the example's sake)
public class Singleton
{
private static Singleton _instance;
public static Singleton Instance
{
get
{
if (_instance == null)
{
// This is the original code.
//_instance = new Singleton();
// This is newer code, after I extended Singleton with
// a better implementation.
_instance = new BetterSingleton();
}
return _instance;
}
}
public virtual void ActualMethod() { // whatever }
}
public class BetterSingleton : Singleton
{
public override void ActualMethod() { // newer implementation }
}
We still have a singleton, accessed through the Singleton class's static Instance member. But the exact identity of that instance can be extended through subclassing.

Using singleton instead of a global static instance

I ran into a problem today and a friend recommended I use a global static instance or more elegantly a singleton pattern. I spent a few hours reading about singletons but a few things still escape me.
Background:
What Im trying to accomplish is creating an instance of an API and use this one instance in all my classes (as opposed to making a new connection, etc).
There seems to be about 100 ways of creating a singleton but with some help from yoda I found some thread safe examples. ..so given the following code:
public sealed class Singleton
{
public static Singleton Instance { get; private set; }
private Singleton()
{
APIClass api = new APIClass(); //Can this be done?
}
static Singleton() { Instance = new Singleton(); }
}
How/Where would you instantiate the this new class and how should it be called from a separate class?
EDIT:
I realize the Singleton class can be called with something like
Singleton obj1 = Singleton.Instance();
but would I be able to access the methods within the APIs Class (ie. obj1.Start)? (not that I need to, just asking)
EDIT #2: I might have been a bit premature in checking the answer but I do have one small thing that is still causing me problems. The API is launching just fine, unfortunately Im able to launch two instances?
New Code
public sealed class SingletonAPI
{
public static SingletonAPI Instance { get; private set; }
private SingletonAPI() {}
static SingletonAPI() { Instance = new SingletonAPI(); }
// API method:
public void Start() { API myAPI = new API();}
}
but if I try to do something like this...
SingletonAPI api = SingletonAPI.Instance;
api.Start();
SingletonAPI api2 = SingletonAPI.Instance; // This was just for testing.
api2.Start();
I get an error saying that I cannot start more than one instance.
Why not just add a public APIClass property to your singleton?
public sealed class Singleton
{
public static Singleton Instance { get; private set; }
private APIClass _APIClass;
private Singleton()
{
_APIClass = new APIClass();
}
public APIClass API { get { return _APIClass; } }
static Singleton() { Instance = new Singleton(); }
}
Then your calling site looks like:
Singleton.Instance.API.DoSomething();
Or if you are the author of the API class, you could make it a singleton itself, instead of wrapping it in a singleton:
public sealed class SingletonAPI
{
public static SingletonAPI Instance { get; private set; }
private SingletonAPI() {}
static SingletonAPI() { Instance = new SingletonAPI(); }
// API method:
public void DoSomething() { Console.WriteLine("hi"); }
}
API call:
SingletonAPI.Instance.DoSomething();
Here is the official Microsoft approach.
The beauty of the singleton is that you can use and access it anywhere in your code without having to create an instance of the class. In fact that is it's raison d'etre, a single instance of a class eg
Singleton.Instance.MyValue and Singleton.Instance.DoSomething();
You wouldn't instantiate the class - the pattern you're using basically instantiates itself the first time it's used. The advantage to the method you're using is that it's thread safe (will only instantiate once, no matter how many threads try to access it), lazy (it won't instantiate until you try to access the Singleton class), and simple in implementation.
All you need to do to use this is to do:
Singleton.Instance.MyMethodOnSingleton();
Or, alternatively:
Singleton myInstance = Singleton.Instance; // Will always be the same instance...
myInstance.DoSomething();

Categories

Resources