ISingletonT Interface |
Namespace: VirtualRadar.Interface
The ISingletonT type exposes the following members.
Name | Description | |
---|---|---|
Singleton |
Gets the single instance of the class that should be used throughout the application.
|
All interfaces that are intended to be used as a singleton (i.e. only one instance of them should be used across the entire application) implement this interface. This has a few advantages - it makes the use of a singleton obvious when reading the code, which hopefully avoids the accidental disposal of a singleton object, and the use of singletons can be detected by the unit tests which can then in turn automatically check that mocks of singleton objects are used correctly.
The drawback with this approach is that you must create an instance of the class before you can access the Singleton property. This instance is unused and so it represents a waste of time and memory. Further you might accidentally use the instance instead of its Singleton, which could produce some hard-to-track-down bugs.
An alternate approach would have been to use the facilities in the class factory to register singleton instances of an interface, which would not need a special interface. This would have worked but presents its own set of problems, the most tricky of all being how you handle singletons that are disposable. If you use the class factory approach then you can't tell whether you getting a unique instance of an object or a singleton instance when you resolve an interface, so you always call Dispose and hope the interface's implementation doesn't do anything until the Dispose call is made during program shutdown. This can complicate the implementation of the interface. Using the ISingleton<> approach you can say that all objects created by the class factory are distinct instances, you can assume that it will not return singletons, and if you ask it for a disposable object you will need to dispose of it when you've finished using it.
ILog log = Factory.Singleton.Resolve<ILog>().Singleton;
log.WriteLine("This will appear in the log");
public interface IMyInterface : ISingleton<IMyInterface> { } class Implementation : IMyInterface { private static readonly IMyInterface _Singleton = new Implementation(); public IMyInterface Singleton { get { return _Singleton; } } }