I have got this singleton implementation in MVC project:
public sealed class Singleton<T> where T : class {
private static volatile T _instance;
private static object _lock = new object();
static Singleton() {}
public static T Instance {
get {
if (_instance == null)
lock (_lock) {
if (_instance == null) {
ConstructorInfo constructor = null;
try {
// Binding flags exclude public constructors.
constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null);
}
catch (Exception exception) {
throw new SingletonException(exception);
}
if (constructor == null || constructor.IsAssembly) // Also exclude internal constructors.
throw new SingletonException(string.Format("A private or protected constructor is missing for '{0}'.", typeof(T).Name));
_instance = (T)constructor.Invoke(null);
}
}
return _instance;
}
}
}
Then I have a controller and this Instance method
public static Controller Instance {
get { return Singleton<Controller>.Instance; }
}
In controller constructor I want to load something like this
private Controller() {
int id = Controller.Instance.SqlManager.GetId();
}
This gives me a loop of course and I don't know how to escape from this.
IMHO access via Controller.Instance is for the clients of Controller, internally you should use the controller fields and methods directly, you don't need to know whether your class is being used as a singleton or not.
Related
Am I able to use an instance of once class in another class and file without having to reinstantiate it?
class Start
{
public static Log Log = new Log(...);
}
class Start1
{
Log.Write("New instance!");
}
I have read about having to use a get/set block to do it, but I'm not exactly sure how I would go about that,
Singleton pattern:
public class Log
{
private static Log instance;
private Log() { }
public static Log Instance
{
get
{
return instance ?? (instance = new Log());
}
}
}
Use it by calling Log.Instance, and so on.
To call this using a parameter, you need to do something like this:
public class Log
{
private string foo;
private static Log instance;
public static Log Instance
{
get
{
if (instance == null)
{
throw new InvalidOperationException("Call CreateInstance(-) to create this object");
}
else
{
return instance;
}
}
}
private Log(string foo) { this.foo = foo; }
public static Log CreateInstance(string foo)
{
return instance ?? (instance = new Log(foo));
}
}
However, it is generally a bad idea to use singletons in this manor. Have a look at dependency injection / inversion of control to see how this can be solved.
I am attempting to implement a singleton pattern in an Azure webjob. Debugging locally the instance is never null. It is always set to the singleton object itself. I feel I'm missing something brutally obvious here.
public sealed class HubErrorList
{
private static volatile HubErrorList instance;
private static object syncRoot = new Object();
private HubErrorList() {}
public static HubErrorList Instance
{
get {
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new HubErrorList();
}
}
}
return instance;
}
}
}
The instance will remain null until the property is accessed. Depending on how you're inspecting this, your tooling may be causing that discrepancy.
That being said, a simpler and nicer "lazy initialized" singleton pattern would be to use Lazy<T> instead:
public sealed class HubErrorList
{
private static Lazy<HubErrorList> instance = new Lazy<HubErrorList>(() => new HubErrorList());
private HubErrorList() {}
public static HubErrorList Instance { get { return instance.Value; } }
}
I realized that I should have only one instance of an object called StdSchedulerFactory running at a time. So far I instantiated the object like this
StdSchedulerFactory sf = new StdSchedulerFactory(properties);
And properties is a NameValueCollection.
How can I write a Singleton class for this object so that the variable sf will always have one instance throughout the program?
Part of the Singleton pattern is typically a private constructor, so that other classes can not make new instances.
The workaround for parameters coming from outside the class is to add a "Init" or "Configure" function:
public static void Configure(NameValueCollection properties)
{
}
Of course, if you forget to call this function, you may get behavior you don't want; so you may want to set a "Configured" flag or something like that so your other functions can react appropriately if this function has not yet been called.
Here is a basic Singleton implementation. It is not thread-safe.
public sealed class StdSchedulerFactory
{
private static readonly StdSchedulerFactory instance;
private NameValueCollection _properties;
private StdSchedulerFactory(NameValueCollection properties)
{
_properties = properties;
}
public static StdSchedulerFactory GetInstance(NameValueCollection properties)
{
if (instance == null)
{
instance = new StdSchedulerFactory(properties);
}
else
{
return instance;
}
}
}
this is my two favorite way implementing simple singleton pattern. The second one is just easier when debugging :)
public sealed class SingletonOne
{
private static readonly Lazy<SingletonOne> instance = new Lazy<SingletonOne>(() => new SingletonOne());
private Lazy<Controller> controller = new Lazy<Controller>(() => new Controller(properties));
private static object properties = null;
public static SingletonOne Instance { get { return instance.Value; } }
public Controller GetController(object properties)
{
SingletonOne.properties = properties;
return this.controller.Value;
}
}
public sealed class SingletonTwo
{
private static readonly SingletonTwo instance = new SingletonTwo();
private Controller controller;
private static object properties = null;
public static SingletonTwo Instance
{
get
{
return SingletonTwo.instance;
}
}
public Controller GetController(object properties)
{
SingletonTwo.properties = properties;
if(this.controller == null)
{
this.controller = new Controller(SingletonTwo.properties);
}
return this.controller;
}
}
public class Controller
{
public Controller(object properties) { }
}
I have a number of classes doing different things but using the same Singleton pattern from http://www.yoda.arachsys.com/csharp/singleton.html
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Does anyone have a neat way I can reuse as much of the common Singleton code as possible between the different classes?
For example if I have SingletonJob1 and SingletonJob2 I'd like to be able to change the code in only place if I move to one of the other Singleton patterns.
Edit: Yes as people have pointed out Method 5 from http://www.yoda.arachsys.com/csharp/singleton.html is less code. I did read to the end of the page! I chose method 2 because the Singleton objects relate to hardware devices and I want only want a couple of them initialised and used in any given run of the program. Method 5 will initialise them all straight away.
Is there any reason you're using that version rather than the simpler one which just initializes the instance in the declaration?
public class Singleton
{
private static Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
// Only use this if you really need it - see the page for details
static Singleton() {}
private Singleton()
{
// I assume this logic varies
}
}
This pattern is sufficiently short that I don't think it's much of a problem to include it everywhere.
I would urge you to consider whether you really need that many singletons; they're generally not great for testability etc.
EDIT: If you really, really want laziness and you're using .NET 4, you can get it with the 6th pattern which is on the singleton page's new home:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
public static class Singleton<T> where T: new()
{
static T instance=null;
static readonly object padlock = new object();
public static T Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new T();
}
return instance;
}
}
}
}
So you can use your Singleton for all Classes:
Singleton<YourClass>.Instance.YourMethod();
Try take a look at:
http://www.codeproject.com/KB/architecture/GenericSingletonPattern.aspx
Something like this?
public sealed class Singleton<T>
{
static T instance=null;
static readonly object padlock = new object();
static Func<T> createInstance;
Singleton(Func<T> constructor)
{
createInstance = constructor;
}
public static T Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = createInstance();
}
return instance;
}
}
}
}
I believe this is what you are after. However I strongly recommend avoiding this Singleton (capital S) pattern as it crushes all unit testing souls and makes heaps of things difficult to control.
public class Singleton<T> where T : new()
{
private static T _Instance;
private static readonly object _InstanceLock = new object();
public static T Instance
{
get
{
if (_Instance == null)
{
lock (_InstanceLock)
{
if (_Instance == null)
{
_Instance = new T();
}
}
}
return _Instance;
}
}
}
public class Foo : Singleton<Foo>
{
public void Something()
{
}
}
public class Example
{
public static void Main()
{
Foo.Instance.Something();
}
}
I created a Singleton class in c#, with a public property that I want to initialize when the Singleton is first called.
This is the code I wrote :
public class BL
{
private ISessionFactory _sessionFactory;
public ISessionFactory SessionFactory
{
get { return _sessionFactory; }
set { _sessionFactory = value; }
}
private BL()
{
SessionFactory = Dal.SessionFactory.CreateSessionFactory();
}
private object thisLock = new object();
private BL _instance = null;
public BL Instance
{
get
{
lock (thisLock)
{
if (_instance == null)
{
_instance = new BL();
}
return _instance;
}
}
}
}
As far as I know, when I address the Instance BL object in the BL class for the first time, it should load the constructor and that should initialize the SessionFactory object.
But when I try :
BL.Instance.SessionFactory.OpenSession();
I get a Null Reference Exception, and I see that SessionFactory is null...
why?
This is not a singleton. You should refer to Jon Skeet's excellent guide on singletons in C#. For example, use this pattern:
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;
}
}
}
Notice in particular that instance is static.