1

Currently I trace number of instances of a base class this way:

private static int _instanceCount = 0;

protected BaseClass()
{
    Interlocked.Increment(ref _instanceCount);

    if (_instanceCount > 1)
        throw new Exception("multiple instances detected.");
}

Then I have child classes with constructor like this:

public ChildClass(): base()
{
    // Empty Constructor
}

and I get exceptions of course. I can move the code from BaseClass constructor to ChildClass constructor but it's a kind of redundancy (all children with the same code).

Is there any way to do it in the BaseClass?

Is getting exception means I really tried to create more than one instance of the ChildClass according to above code?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Xaqron
  • 29,931
  • 42
  • 140
  • 205

2 Answers2

3

Is getting exception means I really tried to create more than one instance of the ChildClass according to above code ?

It means there is more than 1 baseclass(-derived) instance.

Is there any way to do it it the BaseClass ?

Do what in the baseclass? This part of the Questions is unclear. You're already doing it in the baseclass.


But your setup won't be very usefull as it will only allow 1 instance of the baseclass and hence of only 1 of the derived classes.

I'll assume you want each derived class to be a Singleton. To implement that in the base class you'll need for instance a static HashSet where you can use the Typename (this.GetType().Name) as key.

H H
  • 263,252
  • 30
  • 330
  • 514
  • So the inheritance process is thread-safe itself. I was thinking maybe the `static` variable in base class is shared among all children. I want one instance of each `child` not the `BaseClass` and you say the code do that in the `BaseClass` (you right). – Xaqron Jan 22 '11 at 10:58
  • I want each child `Singleton` but the problem is I'm using `MEF` and `Lazy` instantiation so I don't have enough control over the instantiation process (although `Lazy` supports thread-safety). I solved it by locks around the call to `Lazy.Value` but still need to be sure about this. – Xaqron Jan 22 '11 at 11:03
  • Inheritance is thread-safe: not applicable. But the static var is definitely shared and _not_ thread-safe. Your current code limits it to 1 per base-class, not 1 per child. – H H Jan 22 '11 at 11:03
  • So how to make it one per child (without moving code to children) ? – Xaqron Jan 22 '11 at 11:20
  • I already gave an idea: register each instance in a static HashSet. make it thread-safe too. – H H Jan 22 '11 at 12:39
2

If you want a Singleton factory, you could consider using an IoC container instead of rolling your own. Many IoC containers support Singleton factory behaviour as a standard feature. For instance you could use Unity.

Tim Lloyd
  • 37,954
  • 10
  • 100
  • 130