This question already has answers here:
Factory vs instance constructors
(10 answers)
Closed 5 years ago.
This question may be too vague or broad, but i figured i'd give it a shot. I've inherited a large .NET project and have run into some things i've not seen before. The most pressing question i have, is what would be the difference between these two declarations? Both of them work, and both types are used in existing code, but i'm wondering if one should be used over the other for performance or security reasons.
var mgr = ManagerFactory.GetInstance<CustomerNotificationManager>();
vs.
CustomerNotificationManager cNotificationMgr = new CustomerNotificationManager();
Both result in an instance of the CustomerNotificationManager class that can be used for any methods within.
Let me know if you need any more info to (hopefully) answer my question. Also, if this question is 'answerable', feel free to suggest a better title.
public class ManagerFactory
{
private static bool singleton = false;
private static Dictionary<string, ManagerBase> instanceHolder = new Dictionary<string, ManagerBase>();
public static bool Singleton
{
get { return ManagerFactory.singleton; }
set { ManagerFactory.singleton = value; }
}
public static T GetInstance<T>() where T : ManagerBase, new()
{
if (singleton)
{
return getSingletonInstance<T>();
}
else
{
return new T();
}
}
private static T getSingletonInstance<T>() where T : ManagerBase, new()
{
lock (instanceHolder)
{
Type genericType = typeof(T);
if (instanceHolder.ContainsKey(genericType.ToString()))
return instanceHolder[genericType.ToString()] as T;
else
{
var instance = new T();
instanceHolder.Add(genericType.ToString(), instance);
return instance;
}
}
}
}
This is called the Factory Pattern, and it's intended to decouple the calling code from both the runtime type of the instance returned, and the details of object creation.
So GetInstance might return SomeSpecialCustomerNotificationManager, or MockCustomerNotificationManager, etc.
And it might perform some configuration on the instance before returning it.
Or it might return a singleton instance or an object from an object pool.
And all of those things could be changed later, or work differently during Unit Testing, etc, without requiring any changes in the code that uses the CustomerNotificationManager.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am very new to using singleton and have a hard time understanding the lazy implementation of singleton in C#.
Assume I have a string which is initially null/empty and when someone does a get call on that string, I have to calculate the string only when it's null/empty, otherwise return the existing string.
My normal implementation looks like this.
public class A
{
private string str = null;
public A()
{
}
public string GetStr()
{
if(String.IsNullOrEmpty(str))
{
str = CalculateStr();
}
return str;
}
}
How can I implement the thread safe version of above example?
Edit #1: CalculateStr() can return null/empty string back. We need to recalculate the next time if that's the case.
Edit #2: The use case is that the variable str should be threadsafe and should be calculated only if its not null/empty.
Edit #3: I don't know if it's called singleton, I know that the example provided above is not thread-safe.
For caching of (deterministic) results of expensive calls, use Lazy<T> - this has an optional LazyThreadSafetyMode parameter allowing you to specify how to resolve concurrency issues.
Update - Assuming CalculateStr is not static
public class A
{
private readonly Lazy<string> _lazyStr;
public A()
{
// Provide a factory method
_lazyStr = new Lazy<string>(() => CalculateStr());
}
public string GetStr()
{
// Lazy retrieval of the value, invokes factory if needed.
return _lazyStr.Value;
}
public string CalculateStr()
{
// Expensive method goes here. Track to ensure method only called once.
Console.WriteLine("Called");
return "Foo";
}
}
The behaviour is as follows, viz:
If nothing ever calls GetStr, then the (presumed expensive) call to CalculateStr is avoided altogether
If GetStr is called more than once, then the value is cached and reused.
If two or more threads concurrently invoke GetStr the first time it is needed, then the LazyThreadSafetyMode will allow you to decide how you want concurrency to be handled. You can either serialize the calls (with ExecutionAndPublication, the default), i.e. block until one of the threads creates a single instance, OR you can concurrently call the factory on all the threads, and one of the invocation results will be cached (PublicationOnly). For expensive calls, you won't want to be using PublicationOnly.
Update - "Retry" if CalculateStr returns null or empty
Note that OP's updated requirement doesn't quite fit the classic 'lazy instantiation' mold - seemingly the CalculateStr method call is unreliable and sometimes returns null. OP's requirement is thus to cache the first non-null response from the method, but not to retry if the initial response is null. Instead of using Lazy, we'll need to do this ourselves. Here's a double-checked lock implementation.
public class A
{
private string _cachedString = null;
private object _syncLock = new object();
public string GetStr()
{
if (_cachedString == null)
{
lock(_syncLock)
{
if (_cachedString == null)
{
var test = CalculateStr();
if (!string.IsNullOrEmpty(test))
{
_cachedString = test;
}
return test;
}
}
}
return _cachedString;
}
public string CalculateStr()
{
// Unreliable, expensive method here.
// Will be called more than once if it returns null / empty.
Console.WriteLine("Called");
return "Foo";
}
}
Note that neither of the above requires a singleton instance - as many A instances can be invoked as needed, and each A instance will (eventually) cache a single non-null value returned from CalculateStr. If a singleton is required, then share the A instance, or use an IoC container to control a single instance of A.
The most simple implementation of a lazy singleton in modern C# in .NET Core is like this:
public class A
{
public static readonly string LazyStr = CalculateStr();
private static string CalculateStr(){}
}
The LazyStr variable will only be initialized at the time that you first need it (because of the static readonly keywords), and afterwards, it will always be the same.
Try it with this simple example:
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Start at {DateTime.Now}");
Console.ReadKey();
Console.WriteLine(A.LazyString);
Console.ReadKey();
Console.WriteLine(A.LazyString);
Console.ReadKey();
}
}
public class A
{
public static readonly String LazyString = CalculateString();
private static string CalculateString()
{
return DateTime.Now.ToString();
}
}
First, your str should be static to be a "Singleton".
Secondly, You could use Lazy<T> in https://learn.microsoft.com/en-us/dotnet/framework/performance/lazy-initialization
And define the singleton like this
private static readonly Lazy<string>
str =
new Lazy<string>
(() => CalculateStr());
By using Lazy<T> you could archive thread-safety without using lock.
Currently I'm facing an issue with Dictionary<ulong, IStoreableObject>, the problem comes when 2 different types that implements IStoreableObject have the same Id, everything messes up.
I came out with something like this in order to "fix it" but I'm not sure if this is a bad design, thread unsafe or if there will be another kind of issues, maybe someone help me to figure out how do I properly separated dictionaries for different types that implement the same interface so if their ids collide there won't be issues? This is my code so far:
using System.Collections.Generic;
namespace SqlExpress
{
internal sealed class Cache<T> where T : IStoreableObject
{
private readonly Dictionary<ulong, T> _cache = new Dictionary<ulong, T>();
private readonly object _lock = new object();
private static Cache<T> _instance = null;
internal static Cache<T> Instance
{
get
{
if (_instance is null)
{
_instance = new Cache<T>();
}
return _instance;
}
}
private Cache() { }
internal void AddOrUpdate(T obj)
{
if (_cache.ContainsKey(obj.Id))
{
_cache[obj.Id] = obj;
}
else
{
lock (_lock)
{
_cache.Add(obj.Id, obj);
}
}
}
internal T Get(ulong id)
{
if (_cache.ContainsKey(id))
{
return _cache[id];
}
return default(T);
}
internal void Remove(ulong id)
{
if (_cache.ContainsKey(id))
{
_cache.Remove(id);
}
}
}
}
Expected behavior:
Let's assume we have 2 Objects, Foo and Bar, they both implements IStoreableObject.
2+ Objects of Foo mustn't have the same Id, and 2+ Objects of Bar mustn't have the same Id either. Anyways, Foo and Bar caches should not related to each other so if an object in Cache<Foo> has the same id of another object in Cache<Bar>, then nothing bad should be happening. This can't be done with Dictionary<ulong, IStoreableObject> since all underlying types are in the same cache, I want them on different caches and each cache should exists once, I mean, only 1 Cache<Foo> should exists as well as 1 Cache<Bar>.
As others have pointed out, the only way to prevent duplicate keys is by including the Type in the key somehow.
You can do that by nesting dictionaries, like this:
Dictionary<Type, Dictionary<ulong, T>> _cache
But I would probably use a ValueTuple:
Dictionary<(Type, ulong), T> _cache
There also is a string concatenation approach $"{typeof(T).Name}_{id}", but that again can generate duplicates if the type happens to have the same name but lives in a separate namespace. So it's best to consider the complete Type.
Also, consider using ConcurrentDictionary as it seems like you're in a multi-threaded environment here.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have two singleton classes in my project.
public class VStateManager : IVState
{
private static readonly object _createLock = new object();
private static VStateManager _vsManager = null;
public static VStateManager GetVStateManager()
{
lock (_createLock)
{
if (_vsManager == null)
{
return new VStateManager();
}
return _vsManager;
}
}
}
public class VTRFactory : IVTR
{
private static VehicleFactory _VTRFactory =null;
private static readonly object _createLock = new object();
public static VehicleFactory GetVTRFactory()
{
lock(_createLock)
{
if(_VTRFactory == null)
{
return new VTRFactory();
}
return _VTRFactory;
}
}
}
My colleague suggested to create a singleton class (something like a singleton factory) that accepts a generic interface and produces both these singleton objects
How can this be done.?
First of all, your classes aren't implementing singleton at all. Look at this:
if (_vsManager == null)
{
return new VStateManager();
}
return _vsManager;
_vsManager will be always null, so multiple instances will be created each time you access the instance. It should be:
if (_vsManager == null)
{
_vsManager = new VStateManager();
}
return _vsManager;
That's the way you ensure only one instance will be created.
Also, I would use a property instead of a function, it's more clear:
public class VStateManager : IVState
{
private static readonly object _createLock = new object();
private static VStateManager _vsManager = null;
public static VStateManager Instance
{
get
{
lock (_createLock)
{
if (_vsManager == null)
{
_vsManager = new VStateManager();
}
return _vsManager;
}
}
}
}
Then you can use per example VStateManager.Instance.XXX.
Second, why you need a third class to create those singletons? When you need to use them accessing GetXXXX would create the needed instance, is there any reason to create those instances before you need them?
If you really need those instances to be initialized before they are needed then you can do something very simple like this:
public static class Initializer()
{
public static void Init()
{
var a = VStateManager.GetVStateManager();
var b = VehicleFactory.GetVTRFactory();
}
}
Then to initialize just call Initializer.Init(). Overcomplicating the code without any reason is the root of all evil in programming, don't try to solve a problem that doesn't exists as that solution can create real problems.
The singleton factory you are looking for can be created using generics. You need to pass the type for which you need to create a singleton instance and the factory will return an instance of that type with making sure that only one instance of that type is created.
The very basic implementation of such singleton factory would look as following.
public static class SingletonFactory
{
private static readonly object lockObject = new object();
//Dictionary to store the singleton objects
private static readonly Dictionary<string, object> singletonObjects = new Dictionary<string, object>();
// Method to retrieve singleton instance.
// Note the constraint "new ()". This indicates that this method can be called for the types which has default constructor.
public static T GetSingletoneInstance<T>() where T:new ()
{
var typeName = typeof(T).Name;
T instance;
lock (lockObject)
{
// Check in the dictionary if the instance already exist.
if (singletonObjects.ContainsKey(typeName))
{
//Retrieve the instance from the dictionary.
instance = (T) singletonObjects[typeName];
}
else
{
// If it does not exist in the dictionary,
// create a new instance
// and store it in the dictionary.
lock (lockObject)
{
instance = new T();
singletonObjects.Add(typeName, instance);
}
}
}
// Return the instance of type "T" either retrieved from dictionary
// or the newly created one.
return instance;
}
}
Following is how you use this factory.
class Program
{
static void Main(string[] args)
{
var vstateManager = SingletonFactory.GetSingletoneInstance<VStateManager>();
var vehicleFactory = SingletonFactory.GetSingletoneInstance<VehicleFactory>();
Console.ReadKey();
}
}
The implementation of SingletonFactory is a very basic version. And it has limitation that it can be used only for the types which have default constructor.
But it can be further extended to use DI module to initialize the instances without worrying about their constructors. Also it can be extended to store the instances in somewhere else then dictionary such as cache, memcaches or database.
I hope this would help you get whatever you are looking for.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
It makes no sense to me why C# doesn't support static methods & static properties in interfaces. In a brief survey of other SO questions on the issue, I come across a variety of answers ranging from "it's apparently an oversight in the design of C# and/or the CLR, and fixing it would break existing code" all the way to "interfaces are meant to interact with objects, and if you find yourself wanting to use interfaces otherwise, you're obviously lacking grey matter and should probably go back to sweeping floors". This question exhibits the full range of such answers.
I need a family of parsers, each with a method that determines if the assembly file contents passed to it matches its platform type. These are stateless entities; there's no reason to have "objects" of these parsers other than that C# interfaces require class instances. If I rip out all the "static" keywords below, this code compiles without error.
public interface IParser
{
static string platformName { get; }
static bool isThisPlatform(string asmFileContents);
static bool parseAsm(string asmFileContents);
}
class PIC32MX_GCC_Parser : IParser
{
public static string platformName { get { return "PIC32MX_GCC"; } }
public static bool isThisPlatform(string asmFileContents)
{
return false; // stub
}
public static bool parseAsm(string asmFileContents)
{
return false; // stub
}
}
class M16C_IAR_Parser : IParser
{
public static string platformName { get { return "M16C_IAR"; } }
public static bool isThisPlatform(string asmFileContents)
{
return false; // stub
}
public static bool parseAsm(string asmFileContents)
{
return false; // stub
}
}
IParser[] parsers =
{
new PIC32MX_GCC_Parser(),
new M16C_IAR_Parser()
};
public IParser findTheRightParser(string asmFileContents)
{
foreach(IParser parser in parsers)
{
if (parser.isThisPlatform(asmFileContents))
{
Console.WriteLine("Using parser: ", parser.platformName);
return parser;
}
}
return null;
}
I'd like to ask why C# won't let me do this, but I know the answer is just "because it doesn't." I know the "workaround" is to just implement them as instance methods which, if necessary, call a static method (which isn't actually necessary in this case).
Since there are a number of people out there (many with high SO rep) who think that putting static methods in interfaces makes no logical sense and if you want to do so there's something wrong with your design, or your head (or both), I'd like some of those people to help me out & give me a good, simple alternative to my code above which uses static methods and doesn't simply "work around" the issue by having instance methods wrap static methods.
There is a need for objects because what you appear to be looking for is dynamic dispatch- you want to be able to call a method on an interface (IParser.Parse), but have the implementation of the method defined by the concrete implementation of the interface. This is classic OOP, and C# (as well as Java) only supports it via instance methods. Singletons eliminate the need for an allocation per call, so that's a good approach. Alternatively you cal use static classes and static methods- but then you are limited to static dispatch, because the caller must know which implementation to call.
In short- it isn't a C# limitation. It's a limitation of most if not all object oriented programming languages.
There are many examples of singleton implementations in the C# literature (for example: http://www.dotnetperls.com/singleton).
To come up with other alternatives requires changing the way that you select your parser. For example, if you wanted to select it via an enum:
enum ParserType {
PIC32MX_GCC,
M16C_IAR,
Other_Parser,
}
Then something like this will work:
public static bool parseAsm(ParserType type, string asmFileContents) {
switch type {
case PIC32MX_GCC:
return PIC32MX_GCC_Parser.ParseAsm(asmFileContents);
case M16C_IAR:
return M16C_IAR_Parser.ParseAsm(asmFileContents);
default:
throw new NotImplementedException("I dont know this parser type");
}
}
You can also do what you are already trying to do, via reflection (but the performance will be very bad):
Type[] parsers =
{
typeof(PIC32MX_GCC_Parser),
typeof(M16C_IAR_Parser)
};
public Type findTheRightParser(string asmFileContents)
{
foreach(Type parser in parsers)
{
// You probably want to cache this
var mi = parser.GetMethod("isThisPlatform", BindingFlags.Static);
if ((Boolean)mi.Invoke(null, new object[] {asmFileContents}))
{
Console.WriteLine("Using parser: ", parser.platformName);
return parser;
}
}
return null;
}
You can't have static interfaces but you can get the behavior you are looking for if you switch to singletons that redirect to the static fields. Because you use a singleton and the singleton holds no data it has a very low memory overhead, only a few bytes per type.
public interface IParser
{
string platformName { get; }
bool isThisPlatform(string asmFileContents);
bool parseAsm(string asmFileContents);
}
class PIC32MX_GCC_Parser : IParser
{
private PIC32MX_GCC_Parser()
{
}
public static string platformName { get { return "PIC32MX_GCC"; } }
public static bool isThisPlatform(string asmFileContents)
{
return false; // stub
}
public static bool parseAsm(string asmFileContents)
{
return false; // stub
}
private static readonly PIC32MX_GCC_Parser _instance = new PIC32MX_GCC_Parser();
public static IParser Instance
{
get { return _instance; }
}
string IParser.platformName { get { return platformName; } }
bool IParser.isThisPlatform(string asmFileContents)
{
return isThisPlatform(asmFileContents);
}
bool IParser.parseAsm(string asmFileContents)
{
return parseAsm(asmFileContents);
}
}
class M16C_IAR_Parser : IParser
{
//..snip
}
Parser[] parsers =
{
PIC32MX_GCC_Parser.Instance,
M16C_IAR_Parser.Instance
};
public IParser findTheRightParser(string asmFileContents)
{
foreach (IParser parser in parsers)
{
if (parser.isThisPlatform(asmFileContents))
{
Console.WriteLine("Using parser: ", parser.platformName);
return parser;
}
}
return null;
}
However if this where me I would just drop the static methods and put all of the data right inside the singleton.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# Threading & Blocking
I am trying to effectively determine which approach is better:
Currently, I have a singleton instance that exposes entities that are loaded in lazy load fashion. I have listed three approaches which each of which has some advantages. The first approach relies solely on double lock pattern to ensure thread safety. The second approach doesn't use locking but it has the potential of double Load in case of a race. The third approach really uses a solution that I am becoming very fond of. (System.Lazy).
For some reason, I feel there is something wrong with the second approach (System.Thread.InterLocked), yet i can't pin point it. Is there a reason to favor one approach over the other? I did cover this in a previous post where I felt the third option is the way to go from now on.
I stripped the code to the barebones to be able explain the design.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TPLDemo
{
public class SomeEntity
{
}
public class MultiThreadedManager
{
private static readonly System.Lazy<MultiThreadedManager> instance = new Lazy<MultiThreadedManager>(() => { return new MultiThreadedManager(); });
private readonly object _syncRoot = new object();
private List<SomeEntity> _inMemoryEntities = null;
private List<SomeEntity> _inMemoryEntitiesUsingLockFreeApproach = null;
private System.Lazy<List<SomeEntity>> _inMemoryUsingLazy = new Lazy<List<SomeEntity>>(() => { return MultiThreadedManager.Instance.LoadFromSomewhere(); });
public static MultiThreadedManager Instance
{
get { return instance.Value; }
}
public IEnumerable<SomeEntity> LazyEntities
{
get
{
return _inMemoryUsingLazy.Value;
}
}
public IEnumerable<SomeEntity> LocklessEntities
{
get
{
if (_inMemoryEntitiesUsingLockFreeApproach == null)
{
do
{
// Is it possible multiple threads hit this at the same time?
} while (System.Threading.Interlocked.CompareExchange<List<SomeEntity>>(ref _inMemoryEntitiesUsingLockFreeApproach, this.LoadFromSomewhere(), null) != null);
}
return _inMemoryEntitiesUsingLockFreeApproach;
}
}
/// <summary>
/// This is thread safe but it involved some locking.
/// </summary>
public IEnumerable<SomeEntity> Entities
{
get
{
if (_inMemoryEntities == null)
{
lock (_syncRoot)
{
if (_inMemoryEntities == null)
{
List<SomeEntity> list = this.LoadFromSomewhere();
_inMemoryEntities = list;
}
}
}
return _inMemoryEntities;
}
}
private List<SomeEntity> LoadFromSomewhere()
{
return new List<SomeEntity>();
}
public void ReloadEntities()
{
// This is sufficient becasue any subsequent call will reload them safely.
_inMemoryEntities = null;
// This is sufficient becasue any subsequent call will reload them safely.
_inMemoryEntitiesUsingLockFreeApproach = null;
// This is necessary becasue _inMemoryUsingLazy.Value is readonly.
_inMemoryUsingLazy = new Lazy<List<SomeEntity>>(() => { return MultiThreadedManager.Instance.LoadFromSomewhere(); });
}
}
}
The third option (Lazy) allows you to configure how it should behave. You can make it behave like (1) or like (2).
In any case, once it is loaded it does not need to lock or interlock internally to hand you back the loaded Value.
So by all means go for System.Lazy.
There is one nasty thing though: If the factory function fails, the exception is stored and thrown everytime the Value property is accessed. This means that this Lazy instance is not ruined. You cannot ever retry. This means that a transient failure (network error, ...) might permanently take down your application until it is manually restarted.
If have complained about this on MS Connect but it is by design.
My solution was to write my own Lazy. It's not hard.