Circular reference problem Singleton - c#

I'm trying to creating a Singleton class like below where MyRepository lies in separate DAL project. It's causing me a circular reference problem because GetMySingleTon() method returns MySingleTon class and needs its access. Same way I need MyRepository access in constructor of MySingleTon class.
public class MySingleTon
{
static MySingleTon()
{
if (Instance == null)
{
MyRepository rep = new MyRepository();
Instance = rep.GetMySingleTon();
}
}
public static MySingleTon Instance { get; private set; }
public string prop1 { get; set; }
public string prop2 { get; set; }
}
UPDATE: I was doing it very wrongly.
I think didn't needed any singleton. Now I've created a class with static properties in a third project and I'm setting it once and accessing it everywhere. And it has solved my problem for now.
Thanks everyone for your answers.

The repository should not return a singleton object, a repository is used to access data and not returning singleton objects. Your repository could by itself be a singleton, but I don't recommend it, and I don't recommend using a singleton for the class using the repository either. In the code you have it seems like the repository needs to be aware of the "business layer" which is all messed up, the relationships should go only one way. I would re-write it as:
public class MySingleTon
{
private MySingleTon()
{
// You constructor logic, maybe create a reference
// to your repository if you need it
}
private static MySingleTon _instance;
public static MySingleTon Instance {
get
{
if(_instance == null)
_instance = new MySingleTon();
return _instance;
}
}
public string prop1 { get; set; }
public string prop2 { get; set; }
}
I don't recommend my solution, but it should solve you problem. What I do recommend is looking into dependency injection and inversion of control since your design seems sort of wrong. Have a look at NInject.
EDIT: One other thing, why does your singleton have several properties that are public? A singleton shouldn't expose properties it should only expose functions, and should mainly be used when you have a utility class like Math or a true singleton like a logger.

Although , it is not good to create such a class intraction and i don't know what is the reason behind this.
but you can do similar to the below code
Create a project called Public Interface and define an interface IMyRepository with the public functions which you want to expose from MyRepository class.
Create a public property in the singleton class which returns IMyRepository and can be set outside the assembly also.
Now , you need to explicitly set this property from the assemblies which reference your singelton assembly and i assume you can create the object of MyRepository class from other assemblies.
Please note : Above solution is only a trick to break the circular reference not the optimal solution.

While having the singleton accessor property within the class itself is a generally used shortcut, in more complicated situations when you need to deal with instances of multiple related classes it may prove the wrong way. The problem is mixing concerns within a single class.
Your MySingleton class shall be rather some MyClass which is implemented in way generally not dependent on the number of instances that will exist on run-time. Likewise MyRepository shall be able to manage and provide any number of MyClass instances. The fact you will be dealing with only a singleton instance of MyClass can be encapsulated into a separate factory (or accessor or whatever you call it) class that will bind MyClass and MyRepository together.
So try to rethink your design in the following way (schematic):
public class MyClass { ... }
public class MyRepository
{
public MyClass GetMyClassInstance(...);
}
public static class MyClassFactory
{
public static MyClass SingletonInstance
{
get
{
if (singletonInstance == null)
singletonInstance = myRepository.GetMyClassInstance(...);
return singletonInstance;
}
}
}
The remaining question is where does myRepository come from. For example, it can be created on program start-up and provisioned into MyclassFactory as a member field.
At the end of the day, a lot can be made easier if you consider using an inversion of control container. The next step is also shift towards interface-based design. That gives you another layer of abstraction and provides more flexibility in terms of interchangeability of implementations.

in addition to the code from Saurabh, you will change the Singleton class by :
public class MySingleTon
{
static MySingleTon()
{
if (Instance == null)
{
Instance = new MySingleTon();
}
}
private MySingleTon(){}
public static MySingleTon Instance { get; private set; }
public IMyRepository MyRepository{ get; set ;}
}

Related

How can I extend a form class to access global variables without having to specify which class it belongs to?

I'm trying to create some global variables that I can access across all classes in my program and use them as if they exist in the same context of each class, i.e. without typing 'gVariables.'
class gVariables
{
public static string VariableA;
public static int VariableB;
public static byte[] VaraibleC;
public static bool AppIsClosing = false;
}
This works in a standard class:
public class SomeClass : gVariables
{
private void SomeMethod()
{
//Dont need to type 'gVariables.'
VariableA = "FooBar";
VariableB = 1024;
}
}
But how can I do this in a class that inherits System.Windows.Forms.Form?
You can create a BaseForm that inherits from Form. And then in each of your Forms (e.g. DerivedForm) you can inherit from the BaseForm. For example:
public class BaseForm : Form
{
public static string VariableA;
public static int VariableB;
public static byte[] VaraibleC;
public static bool AppIsClosing = false;
}
public class DerivedForm : BaseForm
{
}
One way would be to make a base class that has all the globals as members, as Donal has shown you. But as you have said in the comments, you cannot have a common base class for all your classes.
I will tell you a way you can do this, but I am not recommending that you should do this. What I am going to tell you is a way to simulate multiple inheritance in C# (again, not recommended if you do not have a good reason), so you can inherit both your global variables class and the natural parent class.
You can use an interface, and make all your classes implement that interface. To make examples shorter, I will choose only one variable: AppIsClosing.
interface IGlobalVariables
{
public bool AppIsClosing { get; set; }
}
You should have your class containing global variables, which implements IGlobalVariables. To make sure that only one instance is there, we will also implement the singleton pattern.
class GlobalVariables : IGlobalVariables
{
private bool _appIsClosing = false;
private static GlobalVariables _instance = new GlobalVariables();
private GlobalVariables() {}
public static Instance {
get { return _instance }
}
public bool IGlobalVariables.AppIsClosing
{
get { return this._appIsClosing; }
set { this._appIsClosing = value; }
}
}
Then in all other classes, you can do this:
class SomeClass : WhateverYouWantTheParentClassToBe, IGlobalVariables
{
public bool IGlobalVariables.AppIsClosing
{
get { return GlobalVariables.AppIsClosing; }
set { GlobalVariables.AppIsClosing = value; }
}
// other code
}
Assuming you heavily use global variables, now you can refer to the global variable as just AppIsClosing anywhere in your SomeClass.
Your requirement to use global variables (I believe) is not some evil use of global variables. Global variables are bad when you make int temp a global variable (or any other variable that should be local).
The problem I see with my approach is, you can never tell when a member of GlobalVariables is accessed. For example if we try to find references of GlobalVariables.AppIsClosing, Visual Studio will show us a bunch of IGlobalVariables.AppIsClosing implementations, which is utterly useless.
Just use your global class. Having to type few characters is one of the worst reasons to make this kind of awkward design.
I am showing this pattern to you because we had to port a software framework that was written in a legacy language which had multiple inheritance. And this is what we did. We simulated multiple inheritance by interfaces and object aggregation. I think we had a good reason there to use this kind of awkward design patterns.

Extending functionality through interfaces

I have implemented an interface IService that inherits functionality from a series of other interfaces and serves as a common ground for many different services.
Each of these services is being described by an interface, for example:
public interface IServiceOne : IService
{
//...
}
public class ServiceOne : IServiceOne
{
//...
}
Everything up to that point works as expected:
IServiceOne serviceOne = new ServiceOne();
IServiceTwo serviceTwo = new ServiceTwo();
What I have to do now is to add a big list of constants (public variables) to each of these services which will however be different as per service type (for example, IServiceOne will have different constants than IServiceTwo, there will be constants in IServiceOne that will not exist in IServiceTwo, etc).
What I'm trying to achieve is something like that:
IServiceOne serviceOne = new ServiceOne();
var someConstantValue = serviceOne.Const.SomeConstant;
Just because the variables will differ as of service type I decided to implement an extra interface for each of them:
public interface IServiceOneConstants
{
//...
}
and then broaden my IService definition:
public interface IServiceOne : IService, IServiceOneConstants
{
//...
}
public class ServiceOne : IServiceOne
{
//...
}
The problem I have now is that I don't know how to implement the concrete class for IServiceOneConstants. Obviously by the time one of its variables (we called them constants here) will be called it has to be instantiated, so initially I though of a static class but then you cannot expose a static class's functionality through an interface. I then tried to do it with a singleton and expose its instance via a public non-static wrapper:
public class Singleton : IServiceOneConstants
{
private static Singleton _instance;
private Singleton()
{
SomeConstant = "Some value";
}
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
public String SomeConstant { get; set; }
public Singleton Const
{
get
{
return Instance;
}
}
}
I then adjusted the IServiceOneConstants like that:
public interface IServiceOneConstants
{
Singleton Const { get; }
}
but when I call this:
IServiceOne serviceOne = new ServiceOne();
var someConstantValue = serviceOne.Const.SomeConstant;
I get a null reference exception, as .Const is null.
What am I missing here?
You really helped yourself to get confused as possible, by naming different stuff same name ;)
So, first...
what you're trying to do is to access singleton instance through instance property:
public Singleton Const
{
get
{
return Instance;
}
}
then you are using it like:
serviceOne.Const
but that variable was never assigned. In order to assign it, you should make an instance of Singleton class, assign it to serviceOne.Const property and then you might use it.
What you need is probably something like this:
public class ServiceOne : IServiceOne
{
public Singleton Const
{
get
{
return Singleton.Instance;
}
}
}
You need to check to see if the singleton has been instantiated in ServiceOne.Const.SomeConstants` getter. If it's not, you need to instantiate it. Then return the value of the constant.

how to use interface with singleton class

As I go through the differences between Singleton Vs Static class, I came across one point that we can inherit an interface in singleton class and can call singleton through interface for multiple implementation.
I would like some code demonstration with good example, how object orientation can achieve through singleton and not through static.
Thanks,
Although it's hard to tell what exactly you are referring to, one pattern you might be referring to is the Multiton pattern, where you manage a map of named instances as key-value pairs.
That's basically a factory, but each instance is only created once:
I've modified the Wikipedia example a bit to show that you can even derive from a singleton class, as long as your concrete implementations are private and within the original class:
class FooMultiton
{
private static readonly Dictionary<object, FooMultiton> _instances =
new Dictionary<object, FooMultiton>();
// this is the classic good old singleton trick (prevent direct instantiation)
private FooMultiton()
{ }
// you can also have private concrete implementations,
// invisible to the outside world
private class ConcreteFooMultitonOne : FooMultiton
{ }
public static FooMultiton GetInstance(object key)
{
lock (_instances)
{
FooMultiton instance;
// if it doesn't exist, create it and store it
if (!_instances.TryGetValue(key, out instance))
{
// at this point, you can create a derived class instance
instance = new ConcreteFooMultitonOne();
_instances.Add(key, instance);
}
// always return the same ("singleton") instance for this key
return instance;
}
}
}
Also, generally, if a singleton is not a static class, it can implement any interface you want. The only thing that a singleton pattern prevents is instantiation of multiple instances of a singleton class, but that doesn't mean you cannot completely replace the implementation with something else.
For example, if you have a singleton which is not a static class:
interface ICanTalk
{
string Talk();
}
class Singleton : ICanTalk
{
private Singleton() { }
private static readonly Singleton _instance = new Singleton();
public static Singleton Instance
{ get { return _instance; } }
public string Talk()
{ return "this is a singleton"; }
}
You can also have a number of different implementations:
class OtherInstance : ICanTalk
{
public string Talk()
{ return "this is something else"; }
}
Then you are free to choose any implementation you want, but get only a single instance of the Singleton class:
ICanTalk item;
item = Singleton.Instance;
item = new OtherInstance();
item = new YetAnotherInstance();
According to nkr1pr
Every class can implement an interface, and a Singleton is just a "normal" class that makes sure that only one instance of it exists at any point in time apart from the other business logic it may implement. This also means that a Singleton has at least 2 responsibities and this is not good OO design as classes should only have 1 responsibility and make sure they are good at that responsibility, but that is another discussion.
Something like:
public interface MyInterface
{
}
And
public class MySingleton:MyInterface
{
private static MyInterface instance = new MySingleton();
private MySingleton()
{
}
public static MyInterface getInstance()
{
return instance;
}
}
I'm not sure what you are asking, but singleton classes can implement interfaces.
singleton class does not mean static class, one of the method to create a singleton instance is
to make use of static members.
public class MyInterfaceImplementation : IMyInterface
{
private static MyInterfaceImplementation instance;
private static readonly object lockObj = new object();
private MyInterfaceImplementation() { } //private .ctor
public static MyInterfaceImplementation Instance
{
get
{
if (instance == null)
{
lock (lockObj)
{
instance = new MyInterfaceImplementation();
}
}
return instance;
}
}
public void MyInterfaceMethod()
{
//Implement here
}
}

How to make Singleton a Lazy instantiated class?

I have a class which is lazy instantiated by another library. I don't have control over that library code but still need to be sure it cannot create more than one instance of my class.
Is it possible ? how ?
Some simple solutions to this question hides some problems, for a full understanding of this matter I recommend the reading of the following article
http://www.yoda.arachsys.com/csharp/singleton.html
Which concludes with an optimal solution
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
If it's calling your class's constructor, the only thing you can do is throw an exception in the constructor if you determine that an instance was previously created. Since you don't have control over the other library, you wouldn't be able to use a factory method or static property which would normally be the way you control access to a singleton.
Depending on your situation, you may also look into using a lightweight proxy that wraps a singleton instance. In this example, any number of MyObjectProxy can be created but they all defer their implementation to a single instance of MyObject.
public class MyObject {
internal MyObject() {
}
private int _counter;
public int Increment() {
return Interlocked.Increment(ref _counter);
}
}
public class MyObjectProxy {
private static readonly MyObject _singleton = new MyObject();
public MyObjectProxy() {
}
public int Increment() {
return _singleton.Increment();
}
}

Singleton Pattern for C# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need to store a bunch of variables that need to be accessed globally and I'm wondering if a singleton pattern would be applicable. From the examples I've seen, a singleton pattern is just a static class that can't be inherited. But the examples I've seen are overly complex for my needs. What would be the very simplest singleton class? Couldn't I just make a static, sealed class with some variables inside?
Typically a singleton isn't a static class - a singleton will give you a single instance of a class.
I don't know what examples you've seen, but usually the singleton pattern can be really simple in C#:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton() {} // Make sure it's truly lazy
private Singleton() {} // Prevent instantiation outside
public static Singleton Instance { get { return instance; } }
}
That's not difficult.
The advantage of a singleton over static members is that the class can implement interfaces etc. Sometimes that's useful - but other times, static members would indeed do just as well. Additionally, it's usually easier to move from a singleton to a non-singleton later, e.g. passing in the singleton as a "configuration" object to dependency classes, rather than those dependency classes making direct static calls.
Personally I'd try to avoid using singletons where possible - they make testing harder, apart from anything else. They can occasionally be useful though.
There are several Patterns which might be appropriate for you, a singleton is one of the worse.
Registry
struct Data {
public String ProgramName;
public String Parameters;
}
class FooRegistry {
private static Dictionary<String, Data> registry = new Dictionary<String, Data>();
public static void Register(String key, Data data) {
FooRegistry.registry[key] = data;
}
public static void Get(String key) {
// Omitted: Check if key exists
return FooRegistry.registry[key];
}
}
Advantages
Easy to switch to a Mock Object for automated testing
You can still store multiple instances but if necessary you have only one instance.
Disadvantages
Slightly slower than a Singleton or a global Variable
Static Class
class GlobalStuff {
public static String ProgramName {get;set;}
public static String Parameters {get;set;}
private GlobalStuff() {}
}
Advantages
Simple
Fast
Disadvantages
Hard to switch dynamically to i.e. a Mock Object
Hard to switch to another object type if requirements change
Simple Singleton
class DataSingleton {
private static DataSingleton instance = null;
private DataSingleton() {}
public static DataSingleton Instance {
get {
if (DataSingleton.instance == null) DataSingleton.instance = new DataSingleton();
return DataSingleton;
}
}
}
Advantages
None really
Disadvantages
Hard to create a threadsafe singleton, the above Version will fail if multiple threads access the instance.
Hard to switch for a mock object
Personally I like the Registry Pattern but YMMV.
You should take a look at Dependency Injection as it's usually considered the best practice but it's too big a topic to explain here:
Dependency Injection
A Singleton isn't just a static class that can't be inherited. It's a regular class that can be instantiated only once, with everybody sharing that single instance (and making it thread safe is even more work).
The typical .NET code for a Singleton looks something like the following. This is a quick example, and not by any means the best implementation or thread-safe code:
public sealed class Singleton
{
Singleton _instance = null;
public Singleton Instance
{
get
{
if(_instance == null)
_instance = new Singleton();
return _instance;
}
}
// Default private constructor so only we can instanctiate
private Singleton() { }
// Default private static constructor
private static Singleton() { }
}
If you're going to go down the path you're thinking, a static sealed class will work just fine.
Using C# 6 Auto-Property Initializers.
public sealed class Singleton
{
private Singleton() { }
public static Singleton Instance { get; } = new Singleton();
}
Short and clean - I'll be happy to hear the downsides.
I know this Issue is old, but here is another solution using .Net 4.0 or later (including .Net Core and .Net Standard).
First, define your class that will be transformed into a Singleton:
public class ClassThatWillBeASingleton
{
private ClassThatWillBeASingleton()
{
Thread.Sleep(20);
guid = Guid.NewGuid();
Thread.Sleep(20);
}
public Guid guid { get; set; }
}
In this Example Class I've defined one constructor that Sleeps for a while, and then creates one new Guid and save to it's public property. (The Sleep is just for concurrency testing)
Notice that the constructor is private, so that no one can create a new instance of this class.
Now, We need to define the wrapper that will transform this class into a singleton:
public abstract class SingletonBase<T> where T : class
{
private static readonly Lazy<T> _Lazy = new Lazy<T>(() =>
{
// Get non-public constructors for T.
var ctors = typeof(T).GetConstructors(System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic);
if (!Array.Exists(ctors, (ci) => ci.GetParameters().Length == 0))
throw new InvalidOperationException("Non-public ctor() was not found.");
var ctor = Array.Find(ctors, (ci) => ci.GetParameters().Length == 0);
// Invoke constructor and return resulting object.
return ctor.Invoke(new object[] { }) as T;
}, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
public static T Instance
{
get { return _Lazy.Value; }
}
}
Notice that it uses Lazy to create a field _Lazy that knows how to instantiate a class using it's private constructor.
And it defines one Property Instance to access the Value of the Lazy field.
Notice the LazyThreadSafetyMode enum that is passed to the Lazy constructor. It is using ExecutionAndPublication. So only one thread will be allowed to initialize the Value of the Lazy field.
Now, all we have to do is define the wrapped class that will be a singleton:
public class ExampleSingleton : SingletonBase<ClassThatWillBeASingleton>
{
private ExampleSingleton () { }
}
Here is one example of the usage:
ExampleSingleton.Instance.guid;
And one test to assert that two threads will get the same instance of the Singleton:
[Fact()]
public void Instance_ParallelGuid_ExpectedReturnSameGuid()
{
Guid firstGuid = Guid.Empty;
Guid secondGuid = Guid.NewGuid();
Parallel.Invoke(() =>
{
firstGuid = Singleton4Tests.Instance.guid;
}, () =>
{
secondGuid = Singleton4Tests.Instance.guid;
});
Assert.Equal(firstGuid, secondGuid);
}
This test is calling the Value of the Lazy field concurrently, and we want to assert that both instances that will be returned from this property (Value of Lazy) are the same.
More details about this subject can be found at: C# in Depth
So, as far as I am concerned, this is the most concise and simple implementation of the Singleton pattern in C#.
http://blueonionsoftware.com/blog.aspx?p=c6e72c38-2839-4696-990a-3fbf9b2b0ba4
I would, however, suggest that singletons are really ugly patterns... I consider them to be an anti-pattern.
http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx
For me, I prefer to have something like a Repository, implementing IRepository. Your class can declare the dependency to IRepository in the constructor and it can be passed in using Dependency Injection or one of these methods:
http://houseofbilz.com/archive/2009/05/02.aspx
Use your language features.
Mostly simple thread-safe implementation is:
public sealed class Singleton
{
private static readonly Singleton _instance;
private Singleton() { }
static Singleton()
{
_instance = new Singleton();
}
public static Singleton Instance
{
get { return _instance; }
}
}
...what would be the very simplest singleton class?
Just to add one more possible solution. The simplest, most straight forward and easy to use approach I can think of would be something like this:
//The abstract singleton
public abstract class Singleton<T> where T : class
{
private static readonly Lazy<T> instance = new Lazy<T>( CreateInstance, true );
public static T Instance => instance.Value;
private static T CreateInstance()
{
return (T)Activator.CreateInstance( typeof(T), true);
}
}
//This is the usage for any class, that should be a singleton
public class MyClass : Singleton<MyClass>
{
private MyClass()
{
//Code...
}
//Code...
}
//Example usage of the Singleton
class Program
{
static void Main(string[] args)
{
MyClass clazz = MyClass.Instance;
}
}

Categories