In a web app, I need to have only one instance of a class called ProcessManager. One way is to make it a singleton. The other way is to use the HttpApplicationState to make sure I always access the same instance, like this:
public static ProcessManager ProcessManager
{
get
{
HttpApplicationState applicationState = HttpContext.Current.Application;
if (applicationState["ProcessManager"] == null)
{
applicationState["ProcessManager"] = new ProcessManager();
}
return (ProcessManager)applicationState["ProcessManager"];
}
}
Which method is better and why?
Based on the limited description you've given, I would choose a Singleton, because then it doesn't have a dependency on HttpContext.Current, and can be used outside of the ASP.Net pipeline (for example, when you want to write unit tests.)
(As an aside, when you set something into ApplicationState, you also need to first call Lock() on it, and then Unlock() it after you're done writing to it, to make sure it's thread safe.)
Alternately, allow injection of an HttpContext when you create your ProcessManager, such that you can use it with a mocked HttpContext.
if you plan to implement it as singleton,as per Jon Skeet (a.k.a C# guru),he personally prefers the code below
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
(I'm assuming your ProcessManager constructor is private.)
Making it an actual singleton would be best, because such an approach would make it structurally impossible for other programmers that are maintaining your code to accidentally create multiple instances. There's nothing stopping a consumer from accessing the HttpApplicationState directly and removing and replacing the ProcessManager instance. So you must rely on convention to protect the instance of ProcessManager in HttpApplicationState.
Only if there is an actual use case for multiple instances of the class to exist does it make sense to allow multiple instantiations while relying on convention to protect the instance in HttpApplicationState.
Related
So, with the brand new C# 6 we got those neat auto-property initializers. I thought I might as well take advantage of these to make more concise singletons than ever. Apparently someone else got that idea, too.
public sealed class Singleton
{
public static Singleton Instance { get; } = new Singleton();
private Singleton() { /* some initialization code */ }
}
My questions are:
How thread-safe it is?
How lazy it is, or when the instance is actually created? (not a priority, but it would be good for future reference)
Is it a good idea overall?
(it might look similar to this question, but it's not)
Your code will be expanded to the following:
public sealed class Singleton
{
private static readonly Singleton <Instance>k__BackingField = new Singleton();
public static Singleton Instance { get { return <Instance>k__BackingField; } }
private Singleton() { /* some initialization code */ }
}
(<Instance>k__BackingField is the unspeakable name of the compiler-generated field.)
So, the properties of your code will be exactly the same as of the code above. Namely, this pattern is thread-safe and it can be a good idea, depending on circumstances.
Assuming you're not accessing any other static members of this type before accessing Instance, then the exact degree of laziness is up to the runtime. Commonly, it will be something like "the instance is created the first time a method that could access Instance is JIT-compiled", but you don't have any guarantee about this.
If you want to make sure that the instance is created just before Instance is accessed for the first time, add an empty static constructor to your class. (This can have a small negative effect on performance, but that probably won't matter to you.)
Since most of this is not really specific to C# 6, a good source of further information would be Jon Skeet's articles about singletons and static constructors/type initializers.
I use the singleton pattern in a lot of places, sometimes the constructor does nothing, other times it's initialising things.
I wondered if there was a way to set up an abstract class to minimise my code repetition a bit, i.e. I don't need public static readonly Singleton _Instance = new Singleton(); in every single class, just one base class.
I understand interfaces are not an option.
I've tried using the following (taken from here);
public abstract class Singleton<T> where T : new()
{
static Singleton()
{
}
private static readonly T _Instance = new T();
public static T Instance
{
get { return _Instance; }
}
}
The problem with this is that I can't override the constructor for the cases where I need to initialise things.
Is what I'm trying to do even possible? Or should I just keep doing what I'm doing and not worry about a base singleton class?
I wondered if there was a way to set up an abstract class to minimise my code repetition a bit
No, there isn't. As soon as you've got an abstract class, you've got a class which can be instantiated multiple times. I've seen various people try to do something like this, but the end result is either not a singleton or is more complicated than just doing what you're already doing.
Is what I'm trying to do even possible? Or should I just keep doing what I'm doing and not worry about a base singleton class?
You shouldn't try to create a base singleton class - but if I were you I'd try to stop using quite so many singletons in the first place. The singleton pattern is very easily overused, and it's tantamount to an anti-pattern. See if you can refactor towards dependency injection, using a configuration which happens to create only one instance of each of these classes, but where that's a matter of configuration rather than enforced by the class itself.
Aside from anything else, unit testing involving singletons tends to be a pain, simply because it's global state which needs cleaning up between tests etc.
I have some code as shown below. I guess it is Singleton pattern. Why do I need a static constructor. Also what is the advantages of this? Thanks for your reply ...
public sealed class Myclass
{
static Myclass()
{
Myclass.Application = new Myclass();
}
protected Myclass()
{
}
static Myclass _application;
public static Myclass Application
{
get { return Myclass._application; }
protected set { Myclass._application = value; }
}
string _name;
public string Name
{
get { return _name}
protected set { _name= value; }
}
}
To start with, this class is somewhat odd for having a protected constructor. It's not a fatal flaw given that it's sealed, but it's distinctly odd.
There's a potential difference in timing between this code and the nearly-equivalent use of a static variable initializer:
static readonly Myclass _application = new Myclass();
(There's no need for a setter in this case, of course.)
You can't do that with an automatically implemented property though.
Using static initialization in some form gets you "free" thread-safety - you don't need to do any locking in order to get lazy initialization.
You may find my singleton implementation article interesting for more options.
Usage of a type ctor here is a guarantee that singleton instance will be initialized once. It's more simple that double-checked lock pattern, when implementing lazy singleton initialization, but it has disadvantage the same reason - singleton creation may be very expensive, and singleton may never be used during app lifetime.
There is no immediate advantage in the static constructor as opposed to a lazy-instantiated on get approach, other than thread safety as pointed out by Jon Skeet's answer. This may or may not be relevant in your situation, though you don't specify anything. It just makes the code look different, but is going to result in the same functionality.
The "advantage" of the singleton pattern is that is allows easy access to a single instance of a class, basically a sort of "globally" accessible instance of the class.
I say "advantage" as there are many discussions about the Singleton pattern being an anti-pattern. I am on the fence. In a small application this can function OK and most of the proposed alternative solutions involve Dependency Injection frameworks (often sometimes with the life-span of "Singleton"!), which may be impractical on smaller apps.
Just a note, having a sealed class with protected members is pointless - sealed classes cannot be inherited.
If you write in this way you can use auto property and do not actually implement it.
Say like this:
public sealed class Myclass
{
static Myclass()
{
Myclass.Application = new Myclass();
}
.....
public static Myclass Application {get;set;}
...
}
Basically, there is no any practcal advantage if not like this one: code-style.
You have to create the instance of the class somewhere, and that can either be in a static constructor, or in the property that gets the instance.
Anyhow, it's not a good code example that you have found.
It has protected members even though it's sealed, which only makes the code confusing. They should be private.
If you look at the Name property you will notice that it's impossible to set it, so it will always be null.
static constructor it gets called during the loading of the assembly...
EDIT:
thanks jon I was wrong...
now i understand static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced..
I have a class instance which is created by using Activator.CreateInstance() method. That class instance contains helper methods which are frequently used throughout the application. In order to avoid creating the instance multiple times, I'm just thinking about implementing an appropriate caching mechanism.
The following consideration should be taken into account:
1) I can't use static class and methods.
2) There are around 6 instances (1 instance per class) per App Domain.
Your suggestion would be much appreciated!
If you want to avoid creating it multiple times, then don't use the ASP.Net cache object. The cache object specifically does not guarantee that anything you put in it will remain there. In fact it's one of the first things to be cannibalized if the server needs to free up resources.
A better option would be to use the HttpApplicationState object, which should be used to store objects that need to be globally accessible to all sessions. It also has built in thread safety if you access it properly.
The code to do it is as follows:
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["myObject"] = myObject;
HttpContext.Current.Application.Unlock();
Utilizing it is just
var myObject = (MyObject)HttpContext.Current.Application["myObject"];
Use a singleton pattern:
class MySingleton {
private static MySingleton instance;
public MySingleton {
if(instance != null)
// One already created, the only call to this
// should come through Activator
throw...
instance = this;
}
public static MySingleton GetInstance() {
if(instance == null) instance = new MySingleton();
return instance;
}
}
The activator uses the public constructor. Then you can still retrieve the instance through GetInstance().
Ad 1) How about a static container for your instance? Along the lines of a singleton pattern?
Ad 2) 6 singletons or one static generic singleton class.
P.S.: I guess the static restriction is meant only for the helper class itself?
P.P.S.: Using HttpContext.Current.Application would be pretty much the same approach, except slower.
Sounds like a case for a dependency injection container. No matter which one you pick, they all have support for caching like a singleton, and it will do the Activator.CreateInstance part for you.
I like NInject for it's simplicity.
As an exercise, I'm translating parts of our large and battle-hardened Delphi-framework to C#.
Included in this framework is a generic singleton parent class. Of course, implementing a singleton in C# is fairly easy (there is even a Jon Skeet article, so what more could I wish for), but our Delphi singleton has a slightly different take on the pattern: as opposed to publishing an 'instance' property/method, it has a "fake" constructor that always returns the same instance. The essential characteristic of this approach is that the user of the singleton class doesn't know that he is dealing with a singleton:
as far as they know, they just construct any old class and request some information from it.
I want to accomplish the same thing in C# (as an exercise, so it doesn't have to be production-quality code, evil hackery is fine), but so far I've failed.
Any suggestion to make a simple myInstance = new MyClass(); always return the same instance is most welcome!
Additional info
We are talking a convenience-implementation of the singleton pattern, as offered by the framework. It doesn't necessarely have to be a parent-class, but it does have to assist the developers in creating their own singletons as well. Requiring them to manually redirect all their method calls to the single-instance will not make them overflow with joy. :-)
I'm not really interested in debating whether or not this is the right way to deal with singletons, for now I'm just interested in the finer art of c#-tweaking.
You would do a Proxy (Edit: As Tom points out below, the proper design pattern is Monostate):
public class MyClass {
MyActualClass _actual;
public MyClass() {
_actual = MyActualClass. Instance;
}
public DoStuff() {
_actual.DoStuff();
}
}
internal class MyActualClass {
private MyActualClass {
}
public DoStuff() {
...
}
MyActualClass _instance;
public static Instance {
get {
if(_instance == null)
_instance = new MyActualClass()
return _instance;
}
}
}
....
public static void Main() {
var my1 = new MyClass();
var my2 = new MyClass();
}
my1 != my2 but my1.DoStuff() calls the same instance of the method as my2.DoStuff()
This would be simplified even further if you programmed of an interface only.
Edit: The equality problem could partially be solved by making _actual protected internal and overwriting MyClass.Equals(object obj) to check whether this._actual == obj._actual
I believe the Monostate pattern will give you what you need:
"The Monostate gives us the singularity of state that we so treasure in the Singleton, but without all of the static headaches that come along with it."
More here:
http://jeremyjarrell.com/archive/2008/04/21/88.aspx
As far as I know, this cannot be done for real because of how C# handles object instances. In order for a constructor to be called, the instance has to actually be created, and you can't just "return" another object from a constructor.
The best thing I can come up with (other than using a factory method) is to treat the class internally as a Singleton, and create "dummy" instances that all just point back to that original instance, when created. So for example, in your constructor you would check to see if the singleton has been initialized, and if not, would initialize it, then you would basically just proxy each instance's methods and properties back to the singleton.
In this implementation, the singleton needn't even be necessarily the same class, but you could if you wanted to keep things contained.
Update: One drawback of this approach is that although each instance would behave as a singleton, it would still have its own object reference and therefore you might also want to override Equals() for equality comparisons.
I think you could possibly roll something with Remoting.
Update:
A better way would be to wrap a proper singleton class in a struct or lightweight class.
Create the singleton as a static member and make all methods access the single static instance.
class SingletonWrapper {
private static RealSingleton instance = new RealSingleton();
public void methodA() {
instance.methodA();
}
public String getA() {
return instance.getA();
}
}
(This is actually Java code but C# is similar enough, I think. :)
I don't see how you can, as constructors don't use a return statement. You could clone all of the relevant links to the singleton, but it would have local copies of local variables, and be very messy.
Instead have the constructor check if the singleton is instantiated, and if it has been already, throw an exception, or log a warning to the developer who is using the old style code.
How about using a static function to return an object insted of using the new keyword.
static private m_obj my_obj;
static private bool my_new_obj;
static public m_obj create_m_obj()
{
if (my_new_obj == false)
{
my_new_obj = true;
my_obj = new my_obj();
}
return my_obj;
}
Then you have easy full controle over the creation of the object, if I an not mistaken.