Using a Static class as a collection/container of other objects - c#

I have a design question. I'm working with a Coded UI test framework that someone wrote and I am maintaining. I am convinced the way this is designed incorrectly but I thought I would get some other opinions. It's basically a large static class whose sole purpose is to create and return other objects.
Good/Bad...why? I am lobbying to take on a pretty significant refactor and want to please my case convincingly to my manager.
public static class ParentClass
{
private static ChildClass1 childClass1;
private static ChildClass2 childClass2;
// 10+ more of the same
// Properties
public ChildClass1 ChildClass1
{
get
{
if (childClass1 == null)
{
childClass1 = new ChildClass1();
}
return childClass1;
}
}
public ChildClass2 ChildClass2
{
get
{
if (childClass2 == null)
{
childClass2 = new ChildClass2();
}
return childClass2;
}
}
// 10+ more of the same
}
[TestClass]
public class TestClass1
{
[TestMethod]
public void TestMethod1()
{
var x = ParentClass.ChildClass1.SomeMethod();
Assert.IsNotNull(x);
}
[TestMethod]
public void TestMethod2()
{
var x = ParentClass.ChildClass2.SomeMethod();
Assert.IsNotNull(x);
}
// 10+ more of the same
}

This is something like a singleton pattern but it does not become clear from the provided code why it is designed this way.
var x = ParentClass.ChildClass1.SomeMethod();
could easily be replaced with
var x = new ChildClass1().SomeMethod();
and then you can get rid of ParentClass.ChildClass1 and ParentClass.childClass1 unless ParentClass.ChildClass1 is used several times and carries state from method call to method call.
But while this does not really look elegant and might be overly verbose, I would not consider this a major issue.
Personally I would have implemented it this way but it is hard to tell if this would work for all the omitted code.
[TestClass]
public class TestClass1
{
private static void ExecuteTestCore<T>() where T : new(), IHaveAMethod
{
var x = new T().SomeMethod();
Assert.IsNotNull(x);
}
[TestMethod]
public void TestMethod1()
{
TestClass1.ExecuteTestCore<ChildClass1>();
}
[TestMethod]
public void TestMethod2()
{
TestClass1.ExecuteTestCore<ChildClass2>();
}
// 10+ more of the same.
}
internal interface IHaveAMethod
{
void SomeMethod();
}

It's hard to tell if this is "good" or "bad" without knowing how it's used, but I would suggest looking at IoC containers. They offer this type of capability and much more out of the box
In general, IoC containers can be very useful if used as part of Dependency Injection. If you're not using DI then this static class is probably not very helpful
https://stackoverflow.com/questions/2515124/whats-the-simplest-ioc-container-for-c

If you have a hard time suggesting IoC to the suits (as others have suggested).. show them smaller code perhaps?
public class ParentClass<T> where T : class, new() {
private static T _instance = null;
private static readonly object _locker = new object();
public static T GetObject() {
if (_instance == null) {
lock (_locker) {
if (_instance == null) {
return new T();
}
return _instance;
}
}
}
}
(Disclaimer: Not tested. Possibly not the best thread-safe implementation either)
Also: The design as it stands is hard to maintain.. and wreaks of DRY violations.

For what I can see this class is a "singleton container" I think this can be OK.
If exists a better way to do it? I think it depends of the context of usage.
Useful links:
SingletonPattern
ObjectFactory

Related

Resolving concrete types when using polymorphism in Autofac

Consider the following code:
public interface IFileBackup
{
Task Backup(byte[] file);
}
public class BackUpMechanismA : IFileBackup
{
//Implementation
public async Task Backup(byte[] file)
{
//Attempts to backup using mechanism A
}
}
public class BackUpMechanismB : IFileBackup
{
//Implementation
public async Task Backup(byte[] file)
{
//Attempts to backup using mechanism B
}
}
Then the calling class looks like this:
public class Caller
{
private readonly IFileBackup _backupA;
private readonly IFileBackup _backupB;
public Caller(IFileBackup backupA, IFileBackup backupB)
{
_backupA = backupA;
_backupB = backupB;
}
public async Task BackupFile(byte[] file)
{
try
{
await _backupA.Backup(file);
}
catch(SomeException)
{
await _backupB.Backup(file);
}
}
}
So what I'm trying to do here is to use polymorphism. So both BackupMechanismA and BackupMechanismB implements the Backup method in their own way. In the caller I want to attempt the first mechanism and if that doesn't work we catch an exception and try the second approach.
I'm having trouble resolving the correct implementations using Autofac. I have tried with:
builder.RegisterType<BackupMechanismA>().As<IFileBackup>().AsSelf();
builder.RegisterType<BackupMechanismB>().As<IFileBackUp>().AsSelf();
But this won't work because I still need to tell the caller which of the types to resolve. How do I do that in the caller?
Also, I'm in doubt whether this design is really the right design to go with. Before this design I just had one class with two different methods, one for mechanism A and one for mechanism B and then the caller would just call the different methods in the try catch. So I wanted to refactor this because the class got quite big and I wanted to separate the two different mechanisms into their own classes.
So, can I resolve this using Autofac? And is it the right design to go with for this scenario?
Agree with Jogge that iterating IFileBackups would be a better option, but creating an interface for each type is a no go. Instead, you could add a class which provides IEnumerable<IFileBackup> (an aggregate). For example:
public class BackupBundle : IEnumerable<IFileBackup>
{
private readonly List<IFileBackup> _backups = new List<IFileBackup>();
// default constructor creates default implementations
public BackupBundle()
: this(new List<IFileBackup> {new BackUpMechanismA(), new BackUpMechanismB()}) {}
// allow users to add custom backups
public BackupBundle(IEnumerable<IFileBackup> backups)
{
foreach (var backup in backups)
Add(backup);
}
public void Add(IFileBackup backup)
{
if (backup == null) throw new ArgumentNullException(nameof(backup));
_backups.Add(backup);
}
public IEnumerator<IFileBackup> GetEnumerator()
{
foreach (var backup in _backups)
yield return backup;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class Caller
{
private readonly IEnumerable<IFileBackup> _backups;
public Caller(IEnumerable<IFileBackup> backups)
{
_backups = backups ?? throw new ArgumentNullException(nameof(backups));
}
public async Task BackupFile(byte[] file)
{
foreach (var b in _backups)
{
try
{
await b.Backup(file);
break;
}
catch (Exception e) { }
}
}
}
Registration can be done as follows:
builder.RegisterInstance(new BackupBundle()).As<IEnumerable<IFileBackup>>();
builder.RegisterType<Caller>();
which allows you to resolve by class name:
var caller = scope.Resolve<Caller>();
As you see, the BackupBundle has a dependency of BackUpMechanismA and BackUpMechanismB. You could get rid of it by introducing another layer of abstraction but I'd prefer not to do that. My main concern would be to make Caller more robust. You might want to introduce retry logic, timeouts, etc.
Try registering with a name and then resolve using the name:
builder.RegisterType<BackupMechanismA>().Named<IFileBackup>("BackUpMechanismA");
builder.RegisterType<BackupMechanismB>().Named<IFileBackUp>("BackUpMechanismB");
_backupA = container.ResolveNamed<IFileBackUp>
("BackUpMechanismA");
_backupB = container.ResolveNamed<IFileBackUp>
("BackUpMechanismB");
Resolve the instances during runtime, rather than injecting through the constructor. This will let you resolve to the respective type, as needed.
Let me know if this works.
To make your design work, you can try the next approach:
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<BackUpMechanismA>().Keyed<IFileBackup>("A");
builder.RegisterType<BackUpMechanismB>().Keyed<IFileBackup>("B");
builder.RegisterType<Caller>()
.WithParameter((p, ctx) => p.Position == 0, (p, ctx) => ctx.ResolveKeyed<IFileBackup>("A"))
.WithParameter((p, ctx) => p.Position == 1, (p, ctx) => ctx.ResolveKeyed<IFileBackup>("B"));
IContainer container = builder.Build();
var caller = container.Resolve<Caller>();
Console.ReadKey();
}
However in my opinion you probably don't need such a polymorphism here. It will be much more obvious and descriptive to implement something like this:
public async Task BackupFile(byte[] file)
{
try
{
await BackUpToAmazonS3(file);
}
catch (AmazonS3LoadingException)
{
await BackUpToLocalDisk(file);
}
}
In this example it is obvious what is going on. And there in BackUpToAmazonS3 you can use some injected AmazonS3FileBackUp and in BackUpToLocalDisk use LocalDiskFileBackUp or whatever. The point is that you don't need a polymorphism, when you don't plan to change the implementation. In your context it should be clear? that you try to put backup to some remote storage, and then, if it fails, put in on local disk. You don't need to hide the meaning here. This is your logic and should be clear, when you read the code, I suppose. Hope it helps.
In my experience, you're better off by creating an interface for each type:
public interface IFileBackup
{
Task Backup(byte[] file);
}
public interface IBackUpMechanismA : IFileBackup
{
}
public class BackUpMechanismA : IBackUpMechanismA
{
//...
}
public interface IBackUpMechanismB : IFileBackup
{
}
public class BackUpMechanismB : IBackUpMechanismB
{
//...
}
If you don't want that, what you could do is getting injected a list of IFileBackup and just iterate them. If you register BackUpMechanismA first it will be the first in the list. I'm not sure if this is guaranteed, you have to look it up.
public class Caller
{
private readonly ICollection<IFileBackup> _fileBackups;
public Caller(ICollection<IFileBackup> fileBackups)
{
_fileBackups = fileBackups;
}
public async Task BackupFile(byte[] file)
{
foreach (var fileBackup in _fileBackups)
{
try
{
await fileBackup.Backup(file);
break;
}
catch { }
}
}
}

What's another way to get the same functionality as implementing an interface in a static class?

I have made some functions to control hardware. However in the event real hardware is present (G.demomode = true), I would like to also call the real hardware's functions, which implements the same interface.
You can see my attempt below, but the line DVDDHW.setSupply(voltage); isn't quite right, namely because a static class can't implement an interface. Is there a better way to do this?
The end goal is to define an interface (maybe this isn't the right word) to follow for the HW engineer so he can specify the unspecified functions in the interface.
I tried to do my due diligence of searching, and I found several threads on this topic. However, I couldn't wrap my head around how to implement their alternative solutions for my use case. Any help or pointers would be great.
Thanks!
public interface IPowerSupply
{
bool setSupply(double voltage);
}
public static class DVDDHW : IPowerSupply
{
public bool setSupply(double voltage)
{
i2c.write("DVDD ON"); //or something that involves turning the real hardware on
return true;
}
}
public class DVDD : IPowerSupply
{
public bool setSupply(double voltage)
{
DevLog.DevLog.addToLog(string.Format("Supply set: {0}V: ", voltage) + this.GetType().ToString());
if (G.demoMode == false) //demoMode is false because HW is connected
{
DVDDHW.setSupply(voltage); //What is another way to accomplish this?
}
return true;
}
}
//Code to execute below:
foreach PowerSupply ps in PowerSupplyList // List contains an instance of DVDD in this example
{
ps.setSupply(3.5); // Set each supply to 3.5V
}
A singleton is the way to go if you only want one instance of a class that implements an interface.
The MS how-to is https://msdn.microsoft.com/en-us/library/ff650316.aspx.
For your code, the following will work:
public interface IPowerSupply
{
bool setSupply(double voltage);
}
public class DVDDHW : IPowerSupply
{
IPowerSupply _instance;
public static IPowerSupply Instance
{
get
{
if (_instance == null)
_instance = new DVDDHW();
return _instance;
}
}
private DVDDHW() { }
public bool setSupply(double voltage)
{
i2c.write("DVDD ON"); //or something that involves turning the real hardware on
return true;
}
}
public class DVDD : IPowerSupply
{
public bool setSupply(double voltage)
{
DevLog.DevLog.addToLog(string.Format("Supply set: {0}V: ", voltage) + this.GetType().ToString());
if (G.demoMode == false) //demoMode is false because HW is connected
{
DVDDHW.setSupply(voltage); //What is another way to accomplish this?
}
return true;
}
}
//Code to execute below:
foreach PowerSupply ps in PowerSupplyList // List contains an instance of DVDD in this example
{
ps.setSupply(3.5); // Set each supply to 3.5V
}
There are some slight differences in the way that the singleton behaves when compared to a static class. These are important if your application is multi-threaded, or if there is some other code in the constructor that you expect to run when the type is first accessed. If these things don't mean anything to you then you don't have to worry about it :)
EDIT:
As Scott pointed out, the code in the get accessor is unnecessary. A simplified version is this:
public class DVDDHW : IPowerSupply
{
static readonly IPowerSupply _instance = DVDDHW();
public static IPowerSupply Instance
{
get { return _instance; }
}
private DVDDHW() { }
public bool setSupply(double voltage)
{
i2c.write("DVDD ON"); //or something that involves turning the real hardware on
return true;
}
}
Also, this code had a typo (fixed):
//Code to execute below:
foreach IPowerSupply ps in PowerSupplyList // List contains an instance of DVDD in this example
{
ps.setSupply(3.5); // Set each supply to 3.5V
}

Implement Singleton ... With Lock?

On a multithread application (ASP.NET MVC) I need to have a global settings class which contains constants and values taken from Web.Config.
I would like to have this class static, as singleton ... And locked?
public static class Settings {
public static LoggerSettings Logger;
public static MailerSettings Mailer;
public class LoggerSettings {
public String Levels { get { return ConfigurationManager.AppSettings["Logger.Levels"]; } }
public const String Report = "team#xyz.com";
} // LoggerSettings
public class MailerSettings {
public String Contact { get { return ConfigurationManager.AppSettings["Mailer.Contact"]; } }
} // MailerSettings
}
I think I should implement a double lock? No?
I am not sure the best way to do this. Could I, please, get some help?
Thank You,
Miguel
I would like to have this class static, as singleton
To implement a singleton correctly in C#, see Jon Skeet's excellent summary of what does and does not work:
http://csharpindepth.com/Articles/General/Singleton.aspx
I think I should implement a double lock? No?
No. Double-checked locking is a low-lock technique and therefore insanely dangerous on weak memory model hardware. The moment you stray even the slightest from a "blessed" pattern you have abandoned all hope of the program behaving predictably.
The only circumstances under which I would use double-checked locking are when all of the following are true:
Is there is extensive empirical evidence that single-checked locking produces poor performance?
Let's suppose single-checked performance is unacceptable. Single-checked locking usually produces bad performance due to contention, so step one is eliminate the contention. Can you eliminate the contention and get acceptable performance? I would only use double-checked locking if it was impossible to remove the contention or if the performance problem was caused by the several nanoseconds it takes to obtain an uncontended lock. In the latter case: wow, that's a fast program that those nanoseconds are the slowest thing, and wow, you have pretty serious performance requirements if you're counting individual nanoseconds.
Let's suppose that single-checked performance is unacceptable and cannot be fixed. Is there another low-lock technique, like using Interlocked.CompareExchange or Lazy<T> that has acceptable performance? At least you know that CompareExchange and Lazy<T> were written by experts and enforce memory barriers appropriately on all hardware. Don't use double-checked locking if there is a better tool already implemented.
Let's suppose that none of these tools give acceptable performance. Does double-checked locking give acceptable performance? If not then don't use it.
as I see, you only read the data. So you need not lock here IMO.
Use static constructor to init your variables, like Report (made it also static).
Take a look at Jon Skeet's article Implementing the Singleton Pattern in C#
Simplest and good enough option:
public sealed class Settings
{
private static readonly Settings instance = new Settings();
public LoggerSettings Logger { get; private set; }
public MailerSettings Mailer { get; private set; }
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Settings()
{
}
private Settings()
{
Logger = new LoggerSettings();
Mailer = new MailerSettings();
}
public static Settings Instance { get { return instance;} }
}
public class LoggerSettings {
public LoggerSettings()
{
Levels = ConfigurationManager.AppSettings["Logger.Levels"];
}
public String Levels { get; private set; }
public const String Report = "team#xyz.com";
}
// Mailer settings would look similar
As you are only reading data from this instance you don't need any locking. The singleton instance is created before any other thread can access it so no need to lock there also.
Usage:
Settings.Instance.Mailer.Contact
if you like it static and as Singleton, try it this way:
public static class Settings {
private static readonly object LockObject = new object();
private static LoggerSetting LoggerInstance;
public static LoggerSetting LoggerSettings {
get {
lock (LockObject) {
if (LoggerInstance == null)
LoggerInstance = new LoggerInstance();
return LoggerInstance;
}
}
}
public class LoggerSetting {
public String Levels {
get { return ConfigurationManager.AppSettings["Logger.Levels"]; }
}
public const String Report = "team#xyz.com";
}
}
and use it by:
string x = Settings.LoggerSEttings.Report;
if you'd still like to go ahead and have a singleton instance
public class MySettings{
private static Object lockObj = new Object();
private MySettings() {} // private .ctor
private static MySettings _instance;
public static MySettings MySingleSettings{
get{
if(_instance == null){
lock(lockObj){
if(_instance == null)
_instance = new MySettings();
}
}
return _instance;
}
}

How to check if a static constructor has been called?

I have some classes that caches data from a database, these classes are loaded with data when their static constructor gets called.
I need to call a static Reload method at all these classes, except those that is not initialized yet.
E.g.: City caches data from a database
public class City
{
public City Get(string key)
{
City city;
FCities.TryGetValue(key, out city);
return city;
}
private static Dictionary<string, City> FCities;
static City()
{
LoadAllCitiesFromDatabase();
}
public static void Reload()
{
LoadAllCitiesFromDatabase();
}
private static void LoadAllCitiesFromDatabase()
{
// Reading all citynames from database (a very slow operation)
Dictionary<string, City> loadedCities = new Dictionary<string, City>();
...
FCities = loadedCities;
}
}
The problem is that City might not have been used yet (it might not be used in this service) and there is no reason to load it from the database then.
My reload all method looks much like this:
public static class ReloadAll
{
public static void Do()
{
foreach (Type classType in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => t.IsClass && !t.IsAbstract))
{
MethodInfo staticReload = classType.GetMethods().FirstOrDefault(m => m.IsStatic && m.IsPublic && m.ReturnType == typeof(void) && m.Name == "Reload" && m.GetParameters().Length == 0);
if (staticReload != null)
{
if (StaticConstructorHasBeenCalled(classType))
staticReload.Invoke(null, null);
}
}
}
private bool StaticConstructorHasBeenCalled(Type classType)
{
// How do I check if static constructor has been called?
return true;
}
}
I need a little help with implementing StaticConstructorHasBeenCalled.
At first glance, I thought this could be an issue where <grin> Quantum Mechanical Copenhagen interpretation might apply ("As soon as you look at it, it changes"). </grin> I.e. anything you do in the class to observe whether it has been initialized would probably cause it to initialize itself...
But you don't have to do it in the class, just keep a list somewhere else (other than in any of these static classes) that is populated by every static class when it gets initialized. Then in your reset function, just iterate through the classes in the list.
If you have several of these classes, how about controlling their instantiation through a factory or manager class.
This could keep track of which have been used and call the reload methods where appropriate.
You should not use long-running operations in the static constructor, or at least, they should not run synchronously. Static constructor run implicitly, and when implicit execution takes significant time, it makes for interesting bugs :)
Also, if you do use static constructors, methods and whatnot that maintain state, try to isolate them in a fully static class, so they will, for most scenarios, act like singletons. I would change the implementation to something along these lines:
public static class CityRepository
{
private static bool areCitiesLoaded;
private List<City> cities;
static CityRepository()
{
areCitiesLoaded = false;
cities = new List<City>();
}
//method that will be called in all other method, to ensure
//that the cities are loaded
private static void EnsureLoad()
{
if (!areCitiesLoaded)
{
LoadAllCitiesFromDatabase();
areCitiesLoaded = true;
}
}
}
public class City {} //city instance methods
you could use the singleton pattern, and add a field that will tell you if the unique instance has already been created
actually no need to make a singleton, just keep your static class, and load the data when the property getter that should return it is called:
static class City
{
static bool _loaded = false;
public bool Loaded { get { return _loaded; } }
public static List<C> Data
{
get
{
if (!_loaded)
{
doLoading();
_loaded = true
}
}
}
}
I asked if there was any way to see if a static constructor was called. I think that the answer was no, but a workaround would be to create a manager that could keep track of repositories.
The goal was to change as little as possible to the existing classes.
My solution to a manager class is:
public static class RepositoryManager
{
public delegate void Reload();
private static List<Reload> FRepositories = new List<Reload>();
public static void Register(Reload repository)
{
lock (FRepositories)
{
FRepositories.Add(repository);
}
repository();
}
public static void ReloadAll()
{
List<Reload> list;
lock (FRepositories)
{
list = new List<Reload>(FRepositories);
}
foreach (Reload repository in list)
repository();
}
}
Using the example with the City class the changes would be limited to the static constructor.
public class City
{
// ...
static City()
{
RepositoryManager.Register(LoadAllCitiesFromDatabase);
}
// ...
}
My ReloadAll method would then be as simple as:
public void ReloadAll()
{
RepositoryManager.ReloadAll();
}
Thank you for all your answers, I have rewarded each of you that suggested some kind of a manager as a solution to the problem.
The drawback of this solution is that whenever someone creates a repository that needs to be reloaded/updated/cleared once in a while they have to remember to use the RepositoryManager.

How to implement a singleton in C#?

How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.
If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.
public static class GlobalSomething
{
public static int NumberOfSomething { get; set; }
public static string MangleString( string someValue )
{
}
}
Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.
Singletons only make sense if both of these conditions are true:
The object must be global
There must only ever exist a single instance of the object
Note that #2 does not mean that you'd like the object to only have a single instance - if thats the case, simply instantiate it only once - it means that there must (as in, it's dangerous for this not to be true) only ever be a single instance.
If you want global, just make a global instance of some (non signleton) object (or make it static or whatever).
If you want only one instance, again, static is your friend. Also, simply instantiate only one object.
Thats my opinion anyway.
Singleton != Global. You seem to be looking for the keyword static.
You can really simplify a singleton implementation, this is what I use:
internal FooService() { }
static FooService() { }
private static readonly FooService _instance = new FooService();
public static FooService Instance
{
get { return _instance; }
}
Hmm, this all seems a bit complex.
Why do you need a dependency injection framework to get a singleton? Using an IOC container is fine for some enterprise app (as long as it's not overused, of course), but, ah, the fella just wants to know about implementing the pattern.
Why not always eagerly instantiate, then provide a method that returns the static, most of the code written above then goes away. Follow the old C2 adage - DoTheSimplestThingThatCouldPossiblyWork...
I would recommend you read the article Exploring the Singleton Design Pattern available on MSDN. It details the features of the framework which make the pattern simple to implement.
As an aside, I'd check out the related reading on SO regarding Singletons.
Ignoring the issue of whether or not you should be using the Singleton pattern, which has been discussed elsewhere, I would implement a singleton like this:
/// <summary>
/// Thread-safe singleton implementation
/// </summary>
public sealed class MySingleton {
private static volatile MySingleton instance = null;
private static object syncRoot = new object();
/// <summary>
/// The instance of the singleton
/// safe for multithreading
/// </summary>
public static MySingleton Instance {
get {
// only create a new instance if one doesn't already exist.
if (instance == null) {
// use this lock to ensure that only one thread can access
// this block of code at once.
lock (syncRoot) {
if (instance == null) {
instance = new MySingleton();
}
}
}
// return instance where it was just created or already existed.
return instance;
}
}
/// <summary>
/// This constructor must be kept private
/// only access the singleton through the static Instance property
/// </summary>
private MySingleton() {
}
}
Static singleton is pretty much an anti pattern if you want a loosely coupled design. Avoid if possible, and unless this is a very simple system I would recommend having a look at one of the many dependency injection frameworks available, such as http://ninject.org/ or http://code.google.com/p/autofac/.
To register / consume a type configured as a singleton in autofac you would do something like the following:
var builder = new ContainerBuilder()
builder.Register(typeof(Dependency)).SingletonScoped()
builder.Register(c => new RequiresDependency(c.Resolve<Dependency>()))
var container = builder.Build();
var configured = container.Resolve<RequiresDependency>();
The accepted answer is a terrible solution by the way, at least check the chaps who actually implemented the pattern.
public class Globals
{
private string setting1;
private string setting2;
#region Singleton Pattern Implementation
private class SingletonCreator
{
internal static readonly Globals uniqueInstance = new Globals();
static SingletonCreator()
{
}
}
/// <summary>Private Constructor for Singleton Pattern Implementaion</summary>
/// <remarks>can be used for initializing member variables</remarks>
private Globals()
{
}
/// <summary>Returns a reference to the unique instance of Globals class</summary>
/// <remarks>used for getting a reference of Globals class</remarks>
public static Globals GetInstance
{
get { return SingletonCreator.uniqueInstance; }
}
#endregion
public string Setting1
{
get { return this.setting1; }
set { this.setting1 = value; }
}
public string Setting2
{
get { return this.setting2; }
set { this.setting2 = value; }
}
public static int Constant1
{
get { reutrn 100; }
}
public static int Constat2
{
get { return 200; }
}
public static DateTime SqlMinDate
{
get { return new DateTime(1900, 1, 1, 0, 0, 0); }
}
}
I like this pattern, although it doesn't prevent someone from creating a non-singleton instance. It can sometimes can be better to educate the developers in your team on using the right methodology vs. going to heroic lengths to prevent some knucklehead from using your code the wrong way...
public class GenericSingleton<T> where T : new()
{
private static T ms_StaticInstance = new T();
public T Build()
{
return ms_StaticInstance;
}
}
...
GenericSingleton<SimpleType> builder1 = new GenericSingleton<SimpleType>();
SimpleType simple = builder1.Build();
This will give you a single instance (instantiated the right way) and will effectively be lazy, because the static constructor doesn't get called until Build() is called.
What you are describing is merely static functions and constants, not a singleton. The singleton design pattern (which is very rarely needed) describes a class that is instantiated, but only once, automatically, when first used.
It combines lazy initialization with a check to prevent multiple instantiation. It's only really useful for classes that wrap some concept that is physically singular, such as a wrapper around a hardware device.
Static constants and functions are just that: code that doesn't need an instance at all.
Ask yourself this: "Will this class break if there is more than one instance of it?" If the answer is no, you don't need a singleton.
hmmm... Few constants with related functions... would that not better be achieved through enums ? I know you can create a custom enum in Java with methods and all, the same should be attainable in C#, if not directly supported then can be done with simple class singleton with private constructor.
If your constants are semantically related you should considered enums (or equivalent concept) you will gain all advantages of the const static variables + you will be able to use to your advantage the type checking of the compiler.
My 2 cent
Personally I would go for a dependency injection framework, like Unity, all of them are able to configure singleton items in the container and would improve coupling by moving from a class dependency to interface dependency.
You can make a simple manual static singleton implementation for your common (non-static) class by adding a static property Instance (name can vary) into it with initialization like this:
public class MyClass
{
private static MyClass _instance;
public static MyClass Instance => _instance ?? (_instance = new MyClass());
// add here whatever constructor and other logic you like or need.
}
Then it can be resolved anywhere from this namespace like this:
var myClass = MyClass.Instance; // without any new keyword
myClass.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticProperty = "new value";
By hiding public constructor, adding a private static field to hold this only instance, and adding a static factory method (with lazy initializer) to return that single instance
public class MySingleton
{
private static MySingleton sngltn;
private static object locker;
private MySingleton() {} // Hides parameterless ctor, inhibits use of new()
public static MySingleton GetMySingleton()
{
lock(locker)
return sngltn?? new MySingleton();
}
}
I have written a class for my project using Singleton pattern. It is very easy to use. Hope it will work for you. Please find the code following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TEClaim.Models
{
public class LogedinUserDetails
{
public string UserID { get; set; }
public string UserRole { get; set; }
public string UserSupervisor { get; set; }
public LogedinUserDetails()
{
}
public static LogedinUserDetails Singleton()
{
LogedinUserDetails oSingleton;
if (null == System.Web.HttpContext.Current.Session["LogedinUserDetails"])
{
oSingleton = new LogedinUserDetails();
System.Web.HttpContext.Current.Session["LogedinUserDetails"] = oSingleton;
}
else
{
oSingleton = (LogedinUserDetails)System.Web.HttpContext.Current.Session["LogedinUserDetails"];
}
//Return the single instance of this class that was stored in the session
return oSingleton;
}
}
}
Now you can set variable value for the above code in your application like this..
[HttpPost]
public ActionResult Login(FormCollection collection)
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
User_Details.UserID = "12";
User_Details.UserRole = "SuperAdmin";
User_Details.UserSupervisor = "815978";
return RedirectToAction("Dashboard", "Home");
}
And you can retrieve those value like this..
public ActionResult Dashboard()
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
ViewData["UserID"] = User_Details.UserID;
ViewData["UserRole"] = User_Details.UserRole;
ViewData["UserSupervisor"] = User_Details.UserSupervisor;
return View();
}
In c# it could be (Thread safe as well as lazy initialization):
public sealed class MySingleton
{
static volatile Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton(), true);
public static MySingleton Instance => _instance.Value;
private MySingleton() { }
}

Categories