Thursday, October 27, 2005

Singletons and Dynamic Loading Assemblies

Again in the pits of the coding jungle I discovered that we were breaking the Singleton design pattern. Basically what we had were public default constructors. This of course would allow anyone or any dynamic assembly loader to create a new instance of what should be a unique object!

To solve this I decided to augment our dynamic loading class to look for an attribute: [SingletonAttribute] or [Singleton]. If it finds this, then it will look for [SingletonInstance] that should be on a public static getter.

Old code:

public class NotQuiteSingleton

{

    private static NotQuiteSingleton _instance = new NotQuiteSingleton();

 

    public static NotQuiteSingleton Instance

    {

        get

        {

            return _instance;

        }

    }

 

    /// REALLY BAD!

    public NotQuiteSingleton()

    {

    }

}



New code:

[Singleton]

public class AuthenticSingleton

{

    private static AuthenticSingleton _instance = new AuthenticSingleton();

 

    [SingletonInstance]

    public static AuthenticSingleton Instance

    {

        get

        {

            return _instance;

        }

    }

 

    // Ahhhh... much better...

    private AuthenticSingleton()

    {

    }

}



Enjoy,

John

No comments:

Post a Comment