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.
Related
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.
Comparing 2 ways of class property defenition (A & B):
// implemention A
public class Cache {
private object m_syncRoot = null;
public object SyncRoot {
get {
if (m_syncRoot == null) {
Interlocked.CompareExchange(ref m_syncRoot, new object(), null);
}
return m_syncRoot;
}
}
}
AND
// implemention B.
public class Cache {
public object SyncRoot { get; } = new object(); // in C# 6.0
}
And finally some where uses cache:
static Cache MyCache = new Cache(); // I don't know if this kind of declaration is thread-safe either
lock (MyCache.SyncRoot) {
....
}
Question:
Since "Cache" will be used as static instance, are both "SyncRoot" creations in [A] & [B] thread-safe ?
Yes, both of the two creation are thread-safe. The difference is in implementation B, the SyncRoot object is created when the Cache instance is created. And in A, SyncRoot is created when it is accessed.
I have my singleton as below:
public class CurrentSingleton
{
private static CurrentSingleton uniqueInstance = null;
private static object syncRoot = new Object();
private CurrentSingleton() { }
public static CurrentSingleton getInstance()
{
if (uniqueInstance == null)
{
lock (syncRoot)
{
if (uniqueInstance == null)
uniqueInstance = new CurrentSingleton();
}
}
return uniqueInstance;
}
}
I would like check, if I will have two thread, are there two different singletons? I think, I shall have two different singletons (with different references), so what I'm doing:
class Program
{
static void Main(string[] args)
{
int currentCounter = 0;
for (int i = 0; i < 100; i++)
{
cs1 = null;
cs2 = null;
Thread ct1 = new Thread(cfun1);
Thread ct2 = new Thread(cfun2);
ct1.Start();
ct2.Start();
if (cs1 == cs2) currentCounter++;
}
Console.WriteLine(currentCounter);
Console.Read();
}
static CurrentSingleton cs1;
static CurrentSingleton cs2;
static void cfun1()
{
cs1 = CurrentSingleton.getInstance();
}
static void cfun2()
{
cs2 = CurrentSingleton.getInstance();
}
}
I suppose that I should got currentCounter = 0 (in this case every two singleton are different - because are creating by other threrad). Unfortunately, I got for example currentCounter = 70 so in 70 cases I have the same singletons... Could you tell me why?
I would like check, if I will have two thread, are there two different singletons
No, there are not. A static field is shared across each entire AppDomain, not each thread.
If you want to have separate values per thread, I'd recommend using ThreadLocal<T> to store the backing data, as this will provide a nice wrapper for per-thread data.
Also, in C#, it's typically better to implement a lazy singleton via Lazy<T> instead of via double checked locking. This would look like:
public sealed class CurrentSingleton // Seal your singletons if possible
{
private static Lazy<CurrentSingleton> uniqueInstance = new Lazy<CurrentSingleton>(() => new CurrentSingleton());
private CurrentSingleton() { }
public static CurrentSingleton Instance // use a property, since this is C#...
{
get { return uniqueInstance.Value; }
}
}
To make a class that provides one instance per thread, you could use:
public sealed class InstancePerThread
{
private static ThreadLocal<InstancePerThread> instances = new ThreadLocal<InstancePerThread>(() => new InstancePerThread());
private InstancePerThread() {}
public static InstancePerThread Instance
{
get { return instances.Value; }
}
}
By default, a static field is a single instance shared by all threads that access it.
You should take a look at the [ThreadStatic] attribute. Apply it to a static field to make it have a distinct instance for each thread that accesses it.
Use of a locking object ensures that only one value gets created; you can verify this by putting some logging in your CurrentSingleton constructor.
However, I think there's a small gap in your logic: imagine that two threads simultaneously call this method, while uniqueInstance is null. Both will evaluate the = null clause, and advance to the locking. One will win, lock on syncRoot, and initialize uniqueInstance. When the lock block ends, the other will get its own lock, and initialize uniqueInstance again.
You need to lock on syncRoot before even testing whether uniqueInstance is null.
No matter what you do you are never going to get currentCounter = 0.
Because we are forgetting the the fact that application/C# code is also running in some thread and there are some priorities set by C# to run the code. If you debug the code by putting break points in Main method and CurrentSingleton you will notice that. By the time you reach and create the new Object for CurrentSingleton, for loop may be iteration 3 or 4 or any number. Iterations are fast and code is comparing null values and Object or Object and null value. And I think this is the catch.
Reed has got point static will always be shared hence you need to change your code in following way
public class CurrentSingleton
{
[ThreadStatic]
private static CurrentSingleton uniqueInstance = null;
private static object syncRoot = new Object();
private CurrentSingleton() { }
public static CurrentSingleton getInstance()
{
if (uniqueInstance == null)
uniqueInstance = new CurrentSingleton();
return uniqueInstance;
}
}
And as per analysis you are getting two different objects at 70th iteration but, that is something just mismatch may be null and Object or Object and null. To get successful two different object you need to use [ThreadStatic]
I've been struggling with this problem for a couple days, and I still am not sure how to solve it.
I've created a container extension for the Unity Container to enable me to easily register decorator classes in the container. This is the implementation I currently have, which is almost identical to the one in this article:
public class DecoratorExtension : UnityContainerExtension
{
private int m_order;
private Dictionary<Type, IList<DecoratorRegistration>> m_typeStacks;
protected override void Initialize()
{
m_typeStacks = new Dictionary<Type, IList<DecoratorRegistration>>();
Context.Registering += AddRegistration;
Context.Strategies.Add(new DecoratorBuildStrategy(m_typeStacks), UnityBuildStage.PreCreation);
}
private void AddRegistration(object _sender, RegisterEventArgs _e)
{
if (_e.TypeFrom == null || !_e.TypeFrom.IsInterface)
return;
GetStack(_e.TypeFrom)
.Add(new DecoratorRegistration {Order = m_order++, Type = _e.TypeTo});
}
private IList<DecoratorRegistration> GetStack(Type _type)
{
if (!m_typeStacks.ContainsKey(_type))
m_typeStacks.Add(_type, new List<DecoratorRegistration>());
return m_typeStacks[_type];
}
}
What this does is use a list for each type, to store all type registrations for the same target type, so that I can reassemble it when Resolve is called, using this build strategy:
internal class DecoratorBuildStrategy : BuilderStrategy
{
private readonly Dictionary<Type, IList<DecoratorRegistration>> m_typeStacks;
internal DecoratorBuildStrategy(Dictionary<Type, IList<DecoratorRegistration>> _typeStacks)
{
m_typeStacks = _typeStacks;
}
public override void PreBuildUp(IBuilderContext _context)
{
var key = _context.OriginalBuildKey;
if (_context.GetOverriddenResolver(key.Type) != null)
return;
// Only interfaces can use decorators.
if (!key.Type.IsInterface)
return;
// Gets the list of types required to build the 'decorated' instance.
// The list is reversed so that the least dependent types are built first.
var decoratorTypes = GetDecoratorTypes(key.Type).Reverse().ToList();
if (!decoratorTypes.Any())
return;
object value = null;
foreach (var type in decoratorTypes)
{
Type typeToBuild = type;
if (typeToBuild.IsGenericTypeDefinition)
{
Type[] genericArgumentTypes = key.Type.GetGenericArguments();
typeToBuild = typeToBuild.MakeGenericType(genericArgumentTypes);
}
value = _context.NewBuildUp(new NamedTypeBuildKey(typeToBuild, key.Name));
// An Override is created so that in the next BuildUp the already
// built object gets used instead of doing the BuildUp again and
// entering an infinite loop
_context.AddResolverOverrides(new DependencyOverride(key.Type, value));
}
_context.Existing = value;
_context.BuildComplete = true;
}
private IEnumerable<Type> GetDecoratorTypes(Type _type)
{
var typeList = m_typeStacks.GetValueOrDefault(_type) ?? new List<DecoratorRegistration>(0);
if (!_type.IsGenericType)
return typeList.Select(_reg => _reg.Type);
// If the type is a generic type, we need to get all open generic registrations
// alongside the closed ones
var openGenericList = m_typeStacks
.GetValueOrDefault(_type.GetGenericTypeDefinition()) ??
new List<DecoratorRegistration>(0);
// The final result is an ordered concatenation of the closed and open registrations
// that should be used for the type
return typeList
.Concat(openGenericList)
.OrderBy(_registration => _registration.Order)
.Select(_reg => _reg.Type);
}
}
This is where the DecoratorRegistration model is used. It is just a pair of type/int that represents the order of the registration. I created this to be able to mix open and closed generic registrations correctly:
internal struct DecoratorRegistration
{
public int Order { get; set; }
public Type Type { get; set; }
}
This works wonders for the most part. The problem started when I had a class that implemented two interfaces, one which was decorated, and one that wasn't.
This is the current test case I'm trying to make work:
private interface IAny<T> {}
private interface IAnotherInterface {}
private class Base<T> : IAnotherInterface, IAny<T> {}
private class Decorator1<T> : IAny<T>
{
internal readonly IAny<T> Decorated;
public Decorator1(IAny<T> _decorated)
{
Decorated = _decorated;
}
}
[TestMethod]
public void DecoratorExtensionDoesNotInterfereWithNormalRegistrations()
{
// Arrange
var container = new UnityContainer()
.AddNewExtension<DecoratorExtension>()
.RegisterType<Base<string>>(new ContainerControlledLifetimeManager())
.RegisterType<IAny<string>, Decorator1<string>>()
.RegisterType<IAny<string>, Base<string>>()
.RegisterType<IAnotherInterface, Base<string>>();
// Act
var decorated = container.Resolve<IAny<string>>();
var normal = container.Resolve<IAnotherInterface>();
var anotherDecorated = container.Resolve<IAny<string>>();
var anotherNormal = container.Resolve<IAnotherInterface>();
// Assert
Assert.IsInstanceOfType(normal, typeof (IAnotherInterface));
Assert.IsInstanceOfType(decorated, typeof (Decorator1<string>));
Assert.AreSame(normal, anotherNormal);
Assert.AreSame(decorated, anotherDecorated);
}
This test should make my intent clear. I wanted singleton classes, but the first call to Resolve, for either IAnotherInterface or IAny<string> results in every subsequent call to return the same thing. Thus, I get an exception:
System.InvalidCastException: Unable to cast object of type 'Decorator1`1[System.String]' to type 'IAnotherInterface'.
on this line:
var normal = container.Resolve<IAnotherInterface>();
I'm not sure what to do here. I had to temporarily disable singletons in our project so that this could work as intended. What I wanted is that the Base<string> instance was a sintleton, but when I requested a IAny<string> it would create a NEW instance with the SAME base being decorated.
This is still using .Net 4.0, so I'm stuck with Unity 2.1 here (shouldn't matter in this case though).
It's been a while since I've solved this, so I figured that it would be good to replicate the answer I got from Randy Levy from the EntLib team here.
It basically boils down to the build key I was using to register the decorator instance. With my code, the instance was actually registered with the base class type, while I needed to register it with the actual decorator type.
This post has the suggested workaround for the issue, which worked very nicely on our end.
I'm not exactly sure if this is what you're looking for, but I think this does the trick in the specific case in your test:
container.RegisterType<IAny<string>, Base<string>>(
new ContainerControlledLifetimeManager(), "Inner");
container.RegisterType<IAny<string>, Decorator1<string>>(
new InjectionConstructor(
new ResolvedParameter(typeof(IAny<string>), "Inner")));
container.Register<IAnotherInterface>(new InjectionFactory(
c => c.Resolve<IAny<string>>("Inner")));
You don't need that extension for that.
I'm writing a wrapper around a class library that I have no control over. In this library is a class (let's call it Target) that I want to ensure is only instantiated once, but it is not, in itself, a singleton. I thought of using the Singleton-Factory pattern like so:
internal sealed class SingletonFactory
{
private static readonly SingletonFactory manager = new SingletonFactory();
private readonly Target target;
private static SingletonFactory() { }
private SingletonFactory()
{
target = new Target();
target.Init("foo");
}
internal static SingletonFactory Instance
{
get { return manager; }
}
internal Target Target
{
get { return target; }
}
}
I can then do:
var targetInstance = SingletonFactory.Instance.Target;
I then thought of simplifying this by making the Factory completely static like this:
internal static class StaticFactory
{
private static readonly Target target;
private static StaticFactory()
{
target = new Target();
target.Init("foo");
}
internal static Target Target
{
get { return target; }
}
}
and access to the target instance becomes:
var targetInstance StaticFactory.Target;
I'm pretty sure this StaticFactory is thread-safe, and provides global access to a single instance of the target class. Is there anything wrong with this that I haven't thought of?
I'm not certain that your constructor is really thread-safe, since it technically could be accessed from different threads at the same time. You could lock on a private static readonly object Lock = new object(); to enforce thread safety there.
If we are talking about C# 4, you might also want to look at Lazy<T> here http://msdn.microsoft.com/de-de/library/ee792409.aspx. It supports a thread-safe creation mode LazyThreadSafetyMode that allows you to find a tradeoff between safety and performance.
Sidenote:
In the end, not using a static class might be a better design decision as you prevent an architecturally invisible dependency and gain the ability to swap implementations. Working with abstract factories addresses that (and also allows a nice unit testing experience).
Same thing really, except yours had the private keyword on the static constructor, which is disallowed.
internal static class StaticFactory
{
public static Target Target = new Target();
static StaticFactory()
{
Target.Init("foo");
}
}
You could get fancy, and shove it all into a Lazy:
public static Lazy<Target> Target =
new Lazy<Target>(() => { var t = new Target(); t.Init(""); return t; });
You could also establish a facade, which would give you the same semantics as Target, but keep it as a single instance. It also gives you room to play with where and when you initialize the Target object.
public class TargetFacade
{
private static Target _target = new Target();
static StaticFactory()
{
_target.Init("foo");
}
//Wrap Target's methods here.
public int Score { get { return _target.Score } };
}