How To: Auto Instantiate Singleton in C #

I want to have a Singleton that will be automatically created when the program starts.

What I mean by "auto instantiated" is that the code in Singleton should run itself when the program starts, without any calls or declarations by other code.

So, I want something like the following to create an instance and write out "MySingleton Instantiated" when the program starts (do nothing without the main code) ...

static class MySingleton
{
    private static MySingleton self = new MySingleton();

    protected MySingleton()
    {
        System.Console.WriteLine("MySingleton Instantiated");
    }
}

except that this does not work, since C # will only initialize the static members of the class when necessary, i.e. when they are accessed by / etc.

So what should I do? It can be done?

I have not done this personally with C ++ (I have not used C ++ for a while), but I am sure that this can be done in C ++, but not sure about C #.

. .


, , - ... ( ), () (, PClass).

PClass , PClasses... , ...

( PClass )... , () , (Singleton) - .

, ( ) ... , .

, .


PS. , , ... , , , #. .

+5
8

IoC, , , , , "" , , - :

public class InitOnLoad : Attribute 
{ 
    public static void Initialise()
    {
        // get a list of types which are marked with the InitOnLoad attribute
        var types = 
            from t in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
            where t.GetCustomAttributes(typeof(InitOnLoad), false).Count() > 0
            select t;

        // process each type to force initialise it
        foreach (var type in types)
        {
            // try to find a static field which is of the same type as the declaring class
            var field = type.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(f => f.FieldType == type).FirstOrDefault();
            // evaluate the static field if found
            if (field != null) field.GetValue(null);
        }
    }
}

[InitOnLoad]
public class Foo
{
    public static Foo x = new Foo();

    private Foo()
    {
        Console.WriteLine("Foo is automatically initialised");
    }
}

public class Bar
{
    public static Bar x = new Bar();

    private Bar()
    {
        Console.WriteLine("Bar is only initialised as required");
    }
}

InitOnLoad.Initialise() .

, , (, Bar ).

, , , , Initialise, ( ", " ), .

+6

.NET (IIRC) .., #. (, ASP.NET) , , , global.asax.cs - # (, winform ..) . , , Main.

: ? ?

+5

, , Singleton IoC.

StructureMap, Castle Windsor, Ninject / Autofac.

, IoC, , , .

, ( ) .

Google " ", .

Factory/ factory.

+4

, , Main. static MySingleton() {} , .

+2

.NET , . PClass.

# DllMain. , , , . "DllMain" PCIass.

+1

, , -, . () # ( , ):

public sealed class Singleton
{
static readonly Singleton _instance = new Singleton();

// private ctor
Singleton() {}

 public static Singleton Instance
 {
  get { return _instance; }
 }
}

!

protected MySingleton()

, , . . =)

+1

, , , .Net. , - , , . . , , - . . , . .

0

" PClass , PClasses..."

, Reflection. , ; , .

, , Instances, , ( , , PClass, , ), PClass ( PClass). PClass , .

public class PClass
{
    private static List<PClass> m_instances;
    public static IList<PClass> Instances
    {
        get
        {
            if (m_instances == null)
                m_instances = LoadInstanceList();
            return m_instances;
        }
    }
    private static List<PClass> LoadInstanceList()
    {
        foreach (var assembly in AppDomain.GetAssemblies())
        {
            foreach (var type in assembly.GetTypes())
            {
                if (type.IsAssignableTo(typeof(PClass)) && type != typeof(PClass))
                    m_instances.Add(Activator.CreateInstance(type));
            }
        }
    }
}
0

All Articles