tags:

views:

87

answers:

3

I have a pair of static fields with a complicated one-time initialization. I want this initialization to happen lazily, a la the standard singleton pattern.

However, the initialization procedure involves both fields, so I can't separate it into two different singletons.

What's the best way to handle this?

+1  A: 

Create a wrapper class that contains the references to both your 'singletons' and make that class the singleton?

Addendum:
If you really want to avoid the second level of indirection with this approach, you can always do it in two stages:

  • create a new singleton that encapsulates the individual singletons (original point)
  • create a singleton for each of the original singletons (with separate backing fields) that is initialised from the combined singleton to guarantee that all singletons are initialised atomically
jerryjvl
A: 

I'm currently doing it like this:

class OuterType {
    //...

    static class FieldInitializer {
        public static readonly SomeType field1, field2;

        static FieldInitializer() {
            //Complicated code that sets both fields together
        }
    }

    //...
}

Does anyone have any other ideas?

SLaks
I bet these two fields actually belong in a class, and not just for convenience. It seems likely that if they need to be initialized together, that they are used together, and may represent some concept either in the problem domain or the solution domain.
John Saunders
See: http://www.yoda.arachsys.com/csharp/singleton.html fifth option. You're basically already doing that.
Jimmy Chandra
A: 

public class MyClass { private static MyClass _instance; private object _field1; private object _field2;

public object Field1
{
 get
 {
   lock(_instance)
   {
    if (_instance._field1 == null || _instance._field2 == null)
    _instance.Init();
   }
   return _instance.field1;
 }
}

public object Field2
{
 get
 {
   lock(_instance)
   {
    if (_instance._field1 == null || _instance._field2 == null)
    _instance.Init();
   }
   return _instance.field2;
 }
}

public static MyClass Instance
{
 get
 {
   if (_instance == null)
   _instance = new MyClass();
   return _instace;
 }
}

public void Init()
{/*Do Init Here*/}

}

Keivan
Not thread-safe
SLaks
Still not that good; see the lower half of the page I linked to in the question (http://www.yoda.arachsys.com/csharp/singleton.html)
SLaks
Thanks alot, that was a great read.
Keivan