Internal global property..bad smell? - c#

I have run into a bit of a desgin issue with some code that I have been working on:
My code basic looks like this:
Main COM wrapper:
public class MapinfoWrapper
{
public MapinfoWrapper()
{
Publics.InternalMapinfo = new MapinfoWrapper();
}
public void Do(string cmd)
{
//Call COM do command
}
public string Eval(string cmd)
{
//Return value from COM eval command
}
}
Public static class to hold internal referance to wrapper:
internal static class Publics
{
private static MapinfoWrapper _internalwrapper;
internal static MapinfoWrapper InternalMapinfo
{
get
{
return _internalwrapper;
}
set
{
_internalwrapper = value;
}
}
}
Code that uses internal wrapper instance:
public class TableInfo
{
public string Name {
get { return Publics.InternalMapinfo.Eval("String comman to get the name"); }
set { Publics.InternalMapinfo.Do("String command to set the name"); }
}
}
Does this smell bad to anyone? Should I be using a internal property to hold a reference to the main wrapper object or should I be using a different design here?
Note: The MapinfoWrapper object will be used by the outside world, so I don't really want to make that a singleton.

You are reducing the testability of your TableInfo class by not injecting the MapInfoWrapper into the class itself. Whether you use a global cache of these MapInfoWrapper classes depends on the class -- you need to decide whether it is necessary or not, but it would improve your design to pass a wrapper into TableInfo and use it there rather than referencing a global copy directly inside TableInfo methods. Do this in conjunction with the definition of an interface (i.e., "refactor to interfaces").
I would also do lazy instantiation in the getter(s) of Publics to make sure the object is available if it hasn't already been created rather than setting it in the constructor of MapInfoWrapper.
public class TableInfo
{
private IMapinfoWrapper wrapper;
public TableInfo() : this(null) {}
public TableInfo( IMapinfoWrapper wrapper )
{
// use from cache if not supplied, could create new here
this.wrapper = wrapper ?? Publics.InternalMapInfo;
}
public string Name {
get { return wrapper.Eval("String comman to get the name"); }
set { wrapper.Do("String command to set the name"); }
}
}
public interface IMapinfoWrapper
{
void Do( string cmd );
void Eval( string cmd );
}
public class MapinfoWrapper
{
public MapinfoWrapper()
{
}
public void Do(string cmd)
{
//Call COM do command
}
public string Eval(string cmd)
{
//Return value from COM eval command
}
}
internal static class Publics
{
private static MapinfoWrapper _internalwrapper;
internal static MapinfoWrapper InternalMapinfo
{
get
{
if (_internalwrapper == null)
{
_internalwrapper = new MapinfoWrapper();
}
return _internalwrapper;
}
}
}
Now, when you test the TableInfo methods, you can mock out the MapInfoWrapper easily by providing your own implementation to the constructor. Ex (assuming a hand mock):
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestTableInfoName()
{
IMapinfoWrapper mockWrapper = new MockMapinfoWrapper();
mockWrapper.ThrowDoException(typeof(ApplicationException));
TableInfo info = new TableInfo( mockWrapper );
info.Do( "invalid command" );
}

I thought about adding this to my original response, but it is really a different issue.
You might want to consider whether the MapinfoWrapper class needs to be thread-safe if you store and use a cached copy. Anytime you use a single, global copy you need to consider if it will be used by more than one thread at a time and build it so that any critical sections (anywhere data may be changed or must be assumed to not change) are thread-safe. If a multithreaded environment must be supported -- say in a web site -- then this might argue against using a single, global copy unless the cost of creating the class is very high. Of course, if your class relies on other classes that are also not thread-safe, then you may need to make your class thread-safe anyway.

Related

c# access to central data

my Situation:
I've got a lot of Data which i need in every corner of my program. Something like Data Paths and so on. I need those informations in various classes.
What is the best way to implement that?
Sample:
class A
{
public string GetPath()
{
return "C:\\";
}
}
class B
{
private void sample()
{
A ab = new A();
string path = ab.GetPath();
}
}
class C
{
private void sample()
{
A ab = new A();
string path = ab.GetPath();
}
}
So in my case i always need to initiate A and A always need to work inside the function "GetPath".
I want to prevent that the "GetPath"-Function always will be processed.
Sounds like dependency injection may be a relevant concept to look into. There are lots of tools and frameworks to help you with advanced versions of this, but the core principle is as follows:
Simplified example:
An interface do declare what you need, without specifying how it will be provided:
interface IDataProvider {
string GetPath();
}
An implementing class to provide it (could be completely different, so long as it implements the interface correctly):
public class DataProvider : IDataProvider(){
private string _path = "";
public GetPath()
{
// Load only first time
if (string.IsNullOrEmpty(_path))
{
// You could return a hard-coded value, like this, or fetch
// data in a more flexible way (config? DB? Web-service? ...?)
_path = #"C:\...";
}
return _path;
}
}
Now pass the implementation in as an instance of the interface wherever you need it:
class C {
IDataProvider _dataProvider;
public C(IDataProvider provider)
{
// This has no knowledge about DataProvider, it only cares
// about this being an instance of an object that implements
// the signature "GetPath()":
_dataProvider = provider;
}
private void Sample()
{
string path = _dataProvider.GetPath();
}
}
Now, from wherever you start up your project:
public class StartApp
{
IDataprovider prov = new DataProvider();
C myC = new C(prov);
myC.Sample();
// ..and similarly for other components,
// use the same Provider-instance:
D yourD = new D(prov);
ED yourE = new E(prov);
}
You could also read config-values from files or a database, or whatever you like in DataProvider. The point here is to fetch the data once, and then use it everywhere via a shared instance.
As BWA says in comments, you should be using a static class for A. In example:
static class A
{
public static string GetPath()
{
return "C:\\";
}
}
A static class, function or variable is one where there is only one within the program, so can be accessed from anywhere. You cannot, however, declare instances of a static class. To access this function, use the following:
string path = A.GetPath();
If you need to declare instances of this class, use a static function or variable to store the path variable instead.
What About encapsulate it before for more secure against sof exception.
not tested code
private string getPath;
public string GetPath
{
get => getPath; set => getPath=value;
}

Some design-pattern suggestions needed

C#. I have a base class called FileProcessor:
class FileProcessor {
public Path {get {return m_sPath;}}
public FileProcessor(string path)
{
m_sPath = path;
}
public virtual Process() {}
protected string m_sath;
}
Now I'd like to create to other classes ExcelProcessor & PDFProcessor:
class Excelprocessor: FileProcessor
{
public void ProcessFile()
{
//do different stuff from PDFProcessor
}
}
Same for PDFProcessor, a file is Excel if Path ends with ".xlsx" and pdf if it ends with ".pdf". I could have a ProcessingManager class:
class ProcessingManager
{
public void AddProcessJob(string path)
{
m_list.Add(Path;)
}
public ProcessingManager()
{
m_list = new BlockingQueue();
m_thread = new Thread(ThreadFunc);
m_thread.Start(this);
}
public static void ThreadFunc(var param) //this is a thread func
{
ProcessingManager _this = (ProcessingManager )var;
while(some_condition) {
string fPath= _this.m_list.Dequeue();
if(fPath.EndsWith(".pdf")) {
new PDFProcessor().Process();
}
if(fPath.EndsWith(".xlsx")) {
new ExcelProcessor().Process();
}
}
}
protected BlockingQueue m_list;
protected Thread m_thread;
}
I am trying to make this as modular as possible, let's suppose for example that I would like to add a ".doc" processing, I'd have to do a check inside the manager and implement another DOCProcessor.
How could I do this without the modification of ProcessingManager? and I really don't know if my manager is ok enough, please tell me all your suggestions on this.
I'm not really aware of your problem but I'll try to give it a shot.
You could be using the Factory pattern.
class FileProcessorFactory {
public FileProcessor getFileProcessor(string extension){
switch (extension){
case ".pdf":
return new PdfFileProcessor();
case ".xls":
return new ExcelFileProcessor();
}
}
}
class IFileProcessor{
public Object processFile(Stream inputFile);
}
class PdfFileProcessor : IFileProcessor {
public Object processFile(Stream inputFile){
// do things with your inputFile
}
}
class ExcelFileProcessor : IFileProcessor {
public Object processFile(Stream inputFile){
// do things with your inputFile
}
}
This should make sure you are using the FileProcessorFactory to get the correct processor, and the IFileProcessor will make sure you're not implementing different things for each processor.
and implement another DOCProcessor
Just add a new case to the FileProcessorFactory, and a new class which implements the interface IFileProcessor called DocFileProcessor.
You could decorate your processors with custom attributes like this:
[FileProcessorExtension(".doc")]
public class DocProcessor()
{
}
Then your processing manager could find the processor whose FileProcessorExtension property matches your extension, and instantiate it reflexively.
I agree with Highmastdon, his factory is a good solution. The core idea is not to have any FileProcessor implementation reference in your ProcessingManager anymore, only a reference to IFileProcessor interface, thus ProcessingManager does not know which type of file it deals with, it just knows it is an IFileProcessor which implements processFile(Stream inputFile).
In the long run, you'll just have to write new FileProcessor implementations, and voila. ProcessingManager does not change over time.
Use one more method called CanHandle for example:
abstract class FileProcessor
{
public FileProcessor()
{
}
public abstract Process(string path);
public abstract bool CanHandle(string path);
}
With excel file, you can implement CanHandle as below:
class Excelprocessor: FileProcessor
{
public override void Process(string path)
{
}
public override bool CanHandle(string path)
{
return path.EndsWith(".xlsx");
}
}
In ProcessingManager, you need a list of processor which you can add in runtime by method RegisterProcessor:
class ProcessingManager
{
private List<FileProcessor> _processors;
public void RegisterProcessor(FileProcessor processor)
{
_processors.Add(processor)
}
....
So LINQ can be used in here to find appropriate processor:
while(some_condition)
{
string fPath= _this.m_list.Dequeue();
var proccessor = _processors.SingleOrDefault(p => p.CanHandle(fPath));
if (proccessor != null)
proccessor.Process(proccessor);
}
If you want to add more processor, just define and add it into ProcessingManager by using
RegisterProcessor method. You also don't change any code from other classes even FileProcessorFactory like #Highmastdon's answer.
You could use the Factory pattern (a good choice)
In Factory pattern there is the possibility not to change the existing code (Follow SOLID Principle).
In future if a new Doc file support is to be added, you could use the concept of Dictionaries. (instead of modifying the switch statement)
//Some Abstract Code to get you started (Its 2 am... not a good time to give a working code)
1. Define a new dictionary with {FileType, IFileProcessor)
2. Add to the dictionary the available classes.
3. Tomorrow if you come across a new requirement simply do this.
Dictionary.Add(FileType.Docx, new DocFileProcessor());
4. Tryparse an enum for a userinput value.
5. Get the enum instance and then get that object that does your work!
Otherwise an option: It is better to go with MEF (Managed Extensibility Framework!)
That way, you dynamically discover the classes.
For example if the support for .doc needs to be implemented you could use something like below:
Export[typeof(IFileProcessor)]
class DocFileProcessor : IFileProcessor
{
DocFileProcessor(FileType type);
/// Implement the functionality if Document type is .docx in processFile() here
}
Advantages of this method:
Your DocFileProcessor class is identified automatically since it implements IFileProcessor
Application is always Extensible. (You do an importOnce of all parts, get the matching parts and Execute.. Its that simple!)

Composing shared parts with different export names via static properties

Needs -
To declare shared exports of the same interface. The exports are marked by unique export names so consumers may import a particular flavor of the export.
To inject a common instance of the class into a set of objects but to not share a common instance across sets of objects [This makes me use shared exports using different keys - one set of objects can use a single key to get satisfy their shared import need]
Here is the export class
public interface IMyExport
{
void Display();
}
public class MyExport : IMyExport
{
private Guid _id = Guid.NewGuid();
public void Display()
{
Console.WriteLine("Instance ID = "+_id);
}
}
and here is how I export instances of the class
public static class ExportInitialization
{
[Export("Type A", typeof(IMyExport)),
Export("Type B", typeof(IMyExport))]
public static IMyExport IceCreamExport
{
get
{
return new MyExport();
}
}
}
Consumers may import specific instances in the following manner
[Export]
public class ImporterA
{
private readonly IMyExport _myExport;
[ImportingConstructor]
public ImporterA([Import("Type A")]IMyExport myExport)
{
_myExport = myExport;
}
public void Display()
{
_myExport.Display();
}
}
[Export]
public class ImporterB
{
private readonly IMyExport _myExport;
[ImportingConstructor]
public ImporterB([Import("Type B")]IMyExport myExport)
{
_myExport = myExport;
}
public void Display()
{
_myExport.Display();
}
}
class Program
{
[Import]
public ImporterA ImporterA { get; set; }
[Import]
public ImporterB ImporterB { get; set; }
static void Main(string[] args)
{
new Program().Run();
}
public void Run()
{
var container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
container.ComposeParts(this);
ImporterA.Display();
ImporterB.Display();
Console.ReadKey();
}
}
This used to work fine with .Net 4.0 but when .Net 4.5 is installed - I get the following ouptut
Instance ID = 78bba41a-0c48-44fc-ae69-f0ead96371f9
Instance ID = 78bba41a-0c48-44fc-ae69-f0ead96371f9
Notice that the same instance of the object is returned for both imports. Am I breaking some undocumented rule regarding exporting via static properties?
I found that exporting the specific instances from two distinct static properties ensures that 2 distinct instances are returned.
[Export("Type A", typeof(IMyExport))]
public static IMyExport ExportA
{
get
{
return new MyExport();
}
}
[Export("Type B", typeof(IMyExport))]
public static IMyExport ExportB
{
get
{
return new MyExport();
}
}
This is puzzling since in the unmodified version the static getter was creating a new instance on every get. Not sure if this is the result of some C#/.Net optimization introduced with 4.5 or if this is a MEF issue
This is related to the MEF parts lifetime.
The default for MEF attributes is that components do not say whether they care to get a new instance each time or not.
Meaning that:
Your ExportAttribute does not specify whether exported instances can or should be shared;
Both of the ImportAttributes do not specify whether their import should be shared or not;
The default behavior of MEF is that, if it is not forbidden from sharing instances, it will. Meaning that, according to the documentation, the behavior of .NET 4.5 is the correct one: the instance of MyExport is shared, given that no-one on either side explicitly forbade sharing.
I think that .NET 4.0 had a bug/discrepancy where the static property was called every time, which resulted in what you observed, that is, non shared instances. And you were relying on that bug. I think that the bug finds its origin in a fundamental, framework-wide expectation for properties - it is very unusual to have a static property create a new, semantically distinct, instance for each property call.
I believe you should:
Replace your static property export with a static method export;
Specify the creation policy to non-shared, on either the Export side or the Import side;

Return an opaque object to the caller without violating type-safety

I have a method which should return a snapshot of the current state, and another method which restores that state.
public class MachineModel
{
public Snapshot CurrentSnapshot { get; }
public void RestoreSnapshot (Snapshot saved) { /* etc */ };
}
The state Snapshot class should be completely opaque to the caller--no visible methods or properties--but its properties have to be visible within the MachineModel class. I could obviously do this by downcasting, i.e. have CurrentSnapshot return an object, and have RestoreSnapshot accept an object argument which it casts back to a Snapshot.
But forced casting like that makes me feel dirty. What's the best alternate design that allows me to be both type-safe and opaque?
Update with solution:
I wound up doing a combination of the accepted answer and the suggestion about interfaces. The Snapshot class was made a public abstract class, with a private implementation inside MachineModel:
public class MachineModel
{
public abstract class Snapshot
{
protected internal Snapshot() {}
abstract internal void Restore(MachineModel model);
}
private class SnapshotImpl : Snapshot
{
/* etc */
}
public void Restore(Snapshot state)
{
state.Restore(this);
}
}
Because the constructor and methods of Snapshot are internal, callers from outside the assembly see it as a completely opaque and cannot inherit from it. Callers within the assembly could call Snapshot.Restore rather than MachineModel.Restore, but that's not a big problem. Furthermore, in practice you could never implement Snapshot.Restore without access to MachineModel's private members, which should dissuade people from trying to do so.
Can MachineModel and Snapshot be in the same assembly, and callers in a different assembly? If so, Snapshot could be a public class but with entirely internal members.
I could obviously do this by
downcasting, i.e. have CurrentSnapshot
return an object, and have
RestoreSnapshot accept an object
argument which it casts back to a
Snapshot.
The problem is that somebody could then pass an instance of an object which is not Snapshot.
If you introduce an interface ISnapshot which exposes no methods, and only one implementation exists, you can almost ensure type-safety at the price of a downcast.
I say almost, because you can not completely prevent somebody from creating another implementation of ISnapshot and pass it, which would break. But I feel like that should provide the desired level of information hiding.
You could reverse the dependency and make Snapshot a child (nested class) of MachineModel. Then Snapshot only has a public (or internal) Restore() method which takes as a parameter an instance of MachineModel. Because Snapshot is defined as a child of MachineModel, it can see MachineModel's private fields.
To restore the state, you have two options in the example below. You can call Snapshot.RestoreState(MachineModel) or MachineModel.Restore(Snapshot)*.
public class MachineModel
{
public class Snapshot
{
int _mmPrivateField;
public Snapshot(MachineModel mm)
{
// get mm's state
_mmPrivateField = mm._privateField;
}
public void RestoreState(MachineModel mm)
{
// restore mm's state
mm._privateField = _mmPrivateField;
}
}
int _privateField;
public Snapshot CurrentSnapshot
{
get { return new Snapshot(this); }
}
public void RestoreState(Snapshot ss)
{
ss.Restore(this);
}
}
Example:
MachineModel mm1 = new MachineModel();
MachineModel.Snapshot ss = mm1.CurrentSnapshot;
MachineModel mm2 = new MachineModel();
mm2.RestoreState(ss);
* It would be neater to have Snapshot.RestoreState() as internal and put all callers outside the assembly, so the only way to do a restore is via MachineModel.RestoreState(). But you mentioned on Jon's answer that there will be callers inside the same assembly, so there isn't much point.
This is an old question, but i was looking for something very similar and I ended up here and between the information reported here and some other I came up with this solution, maybe is a little overkill, but this way the state object is fully opaque, even at the assembly level
class Program
{
static void Main(string[] args)
{
DoSomething l_Class = new DoSomething();
Console.WriteLine("Seed: {0}", l_Class.Seed);
Console.WriteLine("Saving State");
DoSomething.SomeState l_State = l_Class.Save_State();
l_Class.Regen_Seed();
Console.WriteLine("Regenerated Seed: {0}", l_Class.Seed);
Console.WriteLine("Restoring State");
l_Class.Restore_State(l_State);
Console.WriteLine("Restored Seed: {0}", l_Class.Seed);
Console.ReadKey();
}
}
class DoSomething
{
static Func<DoSomething, SomeState> g_SomeState_Ctor;
static DoSomething()
{
Type type = typeof(SomeState);
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
}
Random c_Rand = new Random();
public DoSomething()
{
Seed = c_Rand.Next();
}
public SomeState Save_State()
{
return g_SomeState_Ctor(this);
}
public void Restore_State(SomeState f_State)
{
((ISomeState)f_State).Restore_State(this);
}
public void Regen_Seed()
{
Seed = c_Rand.Next();
}
public int Seed { get; private set; }
public class SomeState : ISomeState
{
static SomeState()
{
g_SomeState_Ctor = (DoSomething f_Source) => { return new SomeState(f_Source); };
}
private SomeState(DoSomething f_Source) { Seed = f_Source.Seed; }
void ISomeState.Restore_State(DoSomething f_Source)
{
f_Source.Seed = Seed;
}
int Seed { get; set; }
}
private interface ISomeState
{
void Restore_State(DoSomething f_Source);
}
}

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