开发者

Tracing instantiation in a base class

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜