I am having a singleton class in my code.
In my main function, I created an object of that class.
Then, I tried to create the clone for that object.
And, it gave me "StackOverflowException".
My code looks like:
namespace SingletonApplication
{
class A : ICloneable
{
private static readonly A A1 = new A();
public A A2 { get { return A1; } }
public object Clone()
{
var obj = ((ICloneable)A1).Clone();
return obj;
}
}
class Program
{
static void Main(string[] args)
{
A obj1 = new A();
A obj2 = (A)(obj1.Clone());
Console.WriteLine(object.ReferenceEquals(obj1.A2, obj2.A2));
Console.ReadKey();
}
}
}
Error:
Singleton, by definition, is meant to be a class with only one instance across entire application.
The StackOverflowException you get is caused by Clone menthod which keeps calling itself.
The requirments are contradictory ones:
Singleton can have at most one instance by its own definition
Clone() method is supposed to produce a clone, a new (== second) instance
Probably a better solution is to return a fake clone (i.e. itself)
// sealed: do not inherit from me (I'm a Singleton) and create a second instance
sealed class A : ICloneable
{
private static readonly A A1 = new A();
//private constructor: do not create instances (I'm a Sinleton)
private A() {}
public A A2 { get { return A1; } }
// We can't create a new clone but can return an existing instance
public object Clone()
{
// Cloned Singleton? Let it be itself
return this;
}
}
Instead of recursively calling Clone on the same object over and over again, you should actually do something to clone that object.
Usually you create a new instance and copy all relevant properties over. Like this:
A newA = new A();
newA.X = this.X;
return newA;
However, there is nothing to copy in your code. The readonly field will stay as it is. I wonder why you need a copy of a singleton since that defeats the purpose of the design pattern. And by the way, you implementation of singleton is quite unique. I advise to read up on singletons and follow some samples there.
The error is caused because You let Clone call itself. resulting in an endless loop
And This is not a singleton. A singleton should look like this
class A
{
private static A instance;
private A() { }
public static A Instance
{
get
{
if (instance == null)
{
instance = new A();
}
return instance;
}
}
}
Related
I extended a singleton class that gets the reference to the singleton object with the following call
SingletonClass.singleton
Now I want that every time I call the singleton variable on my CustomSingletonClass that I get a reference to a CustomSingletonClass and not SingletonClass.
Right now I'm using a typecast to achieve that ((CustomSingletonClass)CustomSingletonClass.singleton)
Do I have to override the singleton property somehow?
Usually singleton use static properties to get the instance of the object (seems like yours is SingletonClass.singleton).
As it is a static call, you can't override this porperty in an inherited object because the call will always be done on the current type, not on the instance (overriding static is just nonsense).
You could try to change the way it works by adding a setter to your singleton and setting the desired instance before any call.
public class A
{
private static A _instance;
public static A Instance
{
get
{
if (_instance == null)
{
_instance = new A();
}
return _instance;
}
set { _instance = value; }
}
}
public class B : A
{
}
A.Instance = new B();
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.
My goal is to have methods init() and complete(result) which will run before and after every method of a chosen class.
Similar to how the ActionFilterAttribute in ASP.NET has OnActionExecuting and OnActionExecuted methods that run before and after whatever method you apply them to.
There are multiple interfaces I would like to apply the same init() and complete(result) methods to, and I want to avoid code duplication and keep code easy to understand if possible.
From what I can tell, there doesn't seem to be an elegant solution. So far, I have 3 options:
Option 1:
public interface MyImportantMethods
{
object f();
object g();
}
public class MyClass : MyImportantMethods
{
public object f()
{
// Do things
}
public object g()
{
// Do things
}
}
public class WrappedMyClass : MyImportantMethods
{
private MyImportantMethods ActualContent;
public MyModifiedClass(MyImportantMethods actualContent)
{
this.ActualContent = actualContent;
}
public object f()
{
init();
object result = this.ActualContent.f();
complete(result);
return result;
}
public object g()
{
init();
object result = this.ActualContent.g();
complete(result);
return result;
}
}
Pros: The class with the implementation is completely separate from
the one which calls init() and complete(), so it is more readable and
simpler to understand.
Cons: It is easy for someone not familiar with the code to use the
wrong one. Requires a different class for each interface I want to
apply it to.
Option 2:
public interface MyImportantMethods
{
object f();
object g();
}
class Wrapper: IDisposable
{
public object result;
public Wrapper()
{
init();
}
void Dispose()
{
complete(result);
}
}
public class MyModifiedClass {
private void f()
{
using (var wrapper = new Wrapper(() => completeF()))
{
// Do Things
wrapper.result = result;
}
}
private void g()
{
using (var wrapper = new Wrapper(() => completeG()))
{
// Do Things
wrapper.result = result;
}
}
}
Pros: Not possible to use the wrong class. May be possible to use one
IDisposable class for all interfaces, if I use a reflection trick
Cons: Code will look much more cluttered and hard to understand for a
new reader, especially if the declaration of wrapper takes multiple
lines or wrapper needs more than one parameter from the result (both
are true in my case). Also relies on the caller to set the result.
Option 3:
public abstract class MyImportantMethodsBase
{
public object f()
{
init();
object result = this.fImplementation();
complete(fResult);
return result;
}
public object g()
{
init();
object result = this.gImplementation();
complete(result);
return result;
}
private abstract object fImplementation();
private abstract object gImplementation();
}
public class MyModifiedClass : MyImportantMethodsBase {
private object void fImplementation()
{
// Do Things
}
private object gImplementation()
{
// Do Things
}
}
Pros: Not possible to use the wrong class. The class with the
implementation is completely separate from the one which calls init()
and complete(), so it is more readable and simpler to understand.
Cons: Less simple for a reader to understand.
Is there really no way as simple and understandable as the ActionFilterAttribute to accomplish my goal?
Perhaps Option 1 with Factory Pattern is enough: Make constructor private so it can't be used the wrong way. Make a static function in the same class to construct the subject object and then create a wrapper object around it, returning that of a type that is the common shared interface.
However, If you have many classes to wrap, runtime code generation (or design time .tt code generation) could help you out. calling WrapperGenerator.Create(newObject) where T is the Interface and newObject is the private constructed object which implements that interface. The Create function reflects on the Interface, then you create a new class on the fly based on that interface which will wrap with the extra function calls around the functions found one the base object. Any newly created wrapper classes would be cached for the same Interface.
class WrapperGenerator
{
static Dictionary<Type,ConstructorInfo> cachedWrappers = new ...();
public static T Create<T>(object wrappedObject)
{
ConstructorInfo wrapperConstructor = null;
var found = cachedWrappers.TryGet(typeof(T), out wrapperConstructor);
if (found)
{
return (T)wrapperConstructor.Invoke(wrappedObject);
}
//cachedWrapper not found
wrapperConstructor = GenerateNewConstructor(typeof(T));
cachedWrappers.Add(typeof(T), wrapperConstructor);
return (T)wrapperConstructor.Invoke(wrappedObject);
}
static long Counter = 0;
static ConstructorInfo GenerateNewConstructor(Type t)
{
var methodList = t.GetMethods(...);
StringBuilder sb = new StringBuilder();
sb.Append("namespace WrapperClasses {\r\n");
var ClassName = "Wrapper" + Counter++;
var InterfaceName = t.FullName;
sb.AppendFormat("public class {0} {{\r\n", ClassName);
sb.AppendFormat("{0} wrappedObject = null;\r\n", ClassName);
sb.AppendFormat("public Wrapper{0}({1} wrappedObject) {"\r\n, ClassName, InterfaceName);
sb.Append(" this.wrappedObject = wrappedObject;\r\n");
sb.Append("}\r\n");
foreach (var m in methodList)
{
sb.AppendFormat("public {0} {1}({2}) {{", m.ReturnType.., m.Name, ParameterDeclarationsSegment(m));
sb.AppendFormat(" init();\r\n");
sb.AppendFormat(" var result = wrappedObject.{0}({1});\r\n", m.Name, ParameterPassthroughSegment(m));
sb.AppendFormat(" complete(result);\r\n");
sb.Append("};\r\n");
}
//ETC.. closing class and namespace
var LoadedAssembly = Compiler.Compile(sb,...);
var getWrapperType = LoadedAssembly.SearchType(ClassName);
return getWrapperType.GetConstructors()[0];
}
}
Note: You should implement locking around the cachedWrappers.
I want instantiate complete class.
I have the Type of class which I want to instantiate.
Activator.createInstance(type) I created Instance.
I searched all field of this instance.
I have a field which is defined in another assembly so I load that and instantiate it.
Again I repeat step 3 and 4 for fields inside that class (nested)
I am creating an instance of every type
//in a1.dll
class class1
{
class2 var1;
//some Method
}
//in a2.dll
class class2
{
class3 var2;
//some Method
}
//in a3.dll
class class3
{
//some Method
}
I have to create instance of the entire class1 type.
So you want to create a class containing other classes.
Here is what you can do:
create a class instance through the Activator class
for each property and field type in the current instance, create a sub instance by calling the method you are in and assign the sub instance to the current instance field or property
The following code may help you start getting a handle on this problem, but please read it carefully, as well as the very important points under it:
public class A
{
public B MyBProperty { get; set; }
public C MyCField;
}
public class B
{
public C MyCField;
}
public class C
{
}
public class Creator
{
static MethodInfo mi;
static Creator()
{
mi = typeof(Creator).GetMethod("Create");
}
public T Create<T>()
{
var createdType = Activator.CreateInstance<T>();
// assign all properties
foreach (var p in typeof(T).GetProperties())
{
try
{
var mig = mi.MakeGenericMethod(p.PropertyType);
p.SetValue(createdType, mig.Invoke(this, null));
}
catch
{
}
}
// assign all fields
foreach (var f in typeof(T).GetFields())
{
try
{
var mig = mi.MakeGenericMethod(f.FieldType);
f.SetValue(createdType, mig.Invoke(this, null));
}
catch
{
}
}
return createdType;
}
}
// to use it:
var c = new Creator();
var a = c.Create<A>(); // should be instantiated
Now for some very important points:
this code is supposed to help you see how you can start, it is very naive
it doesn't check for infinite loops !!!
it doesn't cache any creation mechanisms
it fails if your class cannot be created, for example because it doesn't have a parameterless constructor
it fails silently
don't use it!
There are plenty of ways to automagically create objects, and this code is not a solid example, merely a starting point: if you want to know more, I would recommend reading the code from Autofixture or any other automatic object creation framework. I just hope it will help you look into the right direction.
i am a little confused by multi-thread access risk on a static property in C#.
public class MyClass
{
public static MyClass Static
{
get
{
var c = new MyClass();
c.SomeProperty = "12345";
c.OtherProperty = DateTime.Now.ToString();
return c;
}
}
}
This example class provides a static property that create a new instance of MyClass,
like a method:
public class MyClass
{
public static MyClass Static()
{
var c = new MyClass();
c.SomeProperty = "12345";
c.OtherProperty = DateTime.Now.ToString();
return c;
}
}
Obviously, this property is not a "storage" box for an instance of MyClass, but it behaves like a static method (that, if i reading good a msdn article, is completely thread-safe).
My question is: i risk something with using this concept ?
Especially in a web or multi-thread enviroinment ?
There is a no particular utility in using it, only for simple reading and cleaning code:
MyClass.Static.SomeProperty = "Something";
is more clear than
MyClass.Static().SomeProperty = "Something";
All help will be appreciated
Thanks
In both your examples you're returning a new instance of MyClass every time the property is accessed. There is no danger that you'll have any concurrency issues when multiple threads access the static property method at the same time, because they're actually modifying the properties of their own instance of MyClass and not sharing it between them.
If you had something like this instead:
public class MyClass
{
private static MyClass _myClass;
public static MyClass Static
{
get
{
return _myClass ?? (_myClass = new MyClass());
}
}
}
...then you'd cause problems when two threads attempted to write/read properties of the resulting MyClass instance, because they're operating on the same MyClass reference _myClass.
Even so, there are two issues with the code you've posted:
You need to change it to a method and rename it, because it's actually creating something, not accessing a static version of anything. Then you can operate on the return value. Something like this:
public class MyClass
{
public static MyClass Create()
{
var c = new MyClass();
c.SomeProperty = "12345";
c.OtherProperty = DateTime.Now.ToString();
return c;
}
}
Then use it like this:
var myClass = MyClass.Create();
myClass.SomeProperty = "Stuff";
The way you're setting properties currently means their values aren't persisted, because a new MyClass is created the next time the Static property is accessed.
If when you set SomeProperty you actually want a static instance to be updated you'll need to lock on a static object to solve the multi threading issue - something like this:
public static class MyClass
{
private static readonly object locker = new object();
private static string someProperty;
public void SetSomeProperty(string val)
{
lock (locker)
{
someProperty = val;
}
}
public void GetSomeProperty()
{
lock (locker)
{
return someProperty;
}
}
}
It seems that you are creating a static factory method that will give you a fully instantiated object.
Threading would not be an issue here because every time you call this method or property you are creating a new object. If 2 threads call the same method at the same time they will each keep on working on the object they are dealing with
Having said that - Perhaps you should reexamine how you are using the class - because if you call this in your code
MyClass.Static.SomeProperty = "Something";
You are basically throwing away the object after it has been instantiated
you would need to assign it to a variable and store it. - the next time you call that function you will receive a new object.
Perhaps I was not able to explain properly, my question was referred multithreaded access on static properties.
I can confirm that they are thread-safe, if the returned object is bound to the current thread.
Here is the example of what I implemented:
public interface IObjectFactory
{
T CreateOrReuse<T>() where T : class, new();
T CreateOrReuse<T>(string key) where T : class, new();
T CreateOrReuse<T>(string key, params object[] args) where T : class;
}
public class ThreadObjectFactory : IObjectFactory
{
// implementation to create and store into the Thread Data
}
public class HttpSessionObjectFactory : IObjectFactory
{
// implementation to create and store into the current session
}
Now the singleton:
public class MyClass
{
public int PageLoadCounter = 0;
public static MyClass Static
{
get
{
IObjectFactory factory = new HttpSessionObjectFactory();
return factory.CreateOrReuse<MyClass>();
}
}
}
And this is the final use:
public class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyClass.Static.PageLoadCounter++;
}
}
Thanks for the replies, even if the question was not very clear