I have configuration entity in my .NET CF application and I want to use singleton for this. Configuration can be changed and has to be saved/restored for next time application launch. I want to use xml serialize/deserialize, it also provides a possibility to change configuration over xml file.
The question is how to save and restore singleton? Deserialization creates a new instance of singleton class, but it means that it will be two instances of the singleton class at the moment.
I have found a solution with ISerializable interface, but it seems that it does not work with compact framework
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable%28v=VS.90%29.aspx
Is there any way to obtain the same behavior with .NET CF?
Your singleton most likely uses a private constructor in its pattern. So you'd do something like this:
public class MySingleton
{
private static MySingleton m_instance;
private MySingleton() { }
public static MySingleton Instance
{
get
{
if(m_instance == null)
{
// hydrate m_instance from serialized version
}
return m_instance;
}
}
}
or this:
public class MySingleton
{
private static MySingleton m_instance;
private MySingleton()
{
// load data from config file
}
public static MySingleton Instance
{
get
{
if(m_instance == null)
{
m_instance = new MySingleton();
}
return m_instance;
}
}
}
Related
I have a simple .Net WebAPI that I need to instantiate a class on start (just once). This instance needs to be available to each controller.
How/Where do I load this data on application start (where do I make my instance) and how do I access this instance from each controller? Do I need DI?
Edit: Running Framework, not Core.
Make a singleton class and Initalize it in startup.cs
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
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.
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();
}
}
I have a project consisting of three projects,
WCF service
Asp.net MVC 3 application
Class library.
The one in the class library is my singleton, which I have made like this;
public sealed class Singleton
{
public static Singleton Instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (Instance == null)
Instance = new Singleton();
return Instance;
}
}
}
The thing is, I put a Debug.WriteLinein the constructor, and it gets called twice.
What I am trying to do is use the singleton from the mvc 3 application and from the WCF service, but they make different instances. Why?
EDIT: I tried a treadsafe singleton earlier. It made no difference.
There's a couple of things that could be going on here.
The most likely is that your MVC application and your WCF service are running in different AppDomains. It will be impossible for the code to 'share' the same instance if this is the case.
An alternative and less likely cause, is that because your code is not thread safe multiple instances are created. If the Singleton constructor takes a long time to return then this could be the issue. Since your using MVC3, I'll assume .Net 4, in which case the Lazy class is your friend:
private static readonly Lazy<Singleton> _singleton = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return _singleton.Value; } }
I guess your implementation is not thread safe. check the article: Implementing Singleton in C#
here a thread-safe example: (there are many other ways to do this, more complex and safer, this is just a reference...)
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
I have no experience with WCF, but maybe you should implement a thread safe singleton, see: http://www.yoda.arachsys.com/csharp/singleton.html
If the WCF Service is running as a separate application, it will have it's own instance of the singleton as the two applications do not share memory.
Does the WCF Service run on a different IP Address/port number to the MVC application?
You can use the lazy pattern in .Net 4.0
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()
{
}
}
Source: http://csharpindepth.com/Articles/General/Singleton.aspx
First, your exact code as posted is not working. It is not syntactically correct (the curly braces are not balanced), and there are two public Singleton.Instance members. I assume your original code was like that:
public sealed class Singleton
{
private static Singleton _instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (_instance == null)
Instance = new Singleton();
return _instance;
}
}
}
The problem is probably related to a multi-threading environment. That is, while one of threads is calling new Singleton(), another tried to get Singleton.Instance, which, in turn, called another new Singleton().
You should either use double-checked locking there:
public sealed class Singleton
{
private static Singleton _instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (_instance == null)
lock (typeof(Singleton))
if (_instance == null)
{
var instance = new Singleton();
_instance = instance;
}
return _instance;
}
}
}
or, much easier,
public sealed class Singleton
{
public static readonly Singleton _instance = new Singleton();
private Singleton()
{
}
}
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.