次の方法で共有


Using Object Builder as a singleton factory

One of the most basic uses of Object Builder is when we want to specify that certain objects should always be created as singletons.  For example, we may require that only one instance of a DataAccess object should ever exist.  This can be specified by setting a policy, in this case a SingletonPolicy, that applies to all objects of type DataAccess.

The following example demonstrates how this code might look, and uses the Object Builder to create a DataAccess object four times - twice with the singleton policy enabled and twice without.

 Builder builder = new Builder();
Locator locator = new Locator();

// We need a lifetime container to keep references to the objects
// SingletonStrategy depends on this!
locator.Add(typeof(ILifetimeContainer), new LifetimeContainer());

// Enable singleton policy for DataAccess objects
builder.Policies.Set<ISingletonPolicy>(new SingletonPolicy(true), typeof(DataAccess), null);

SingletonPolicyDemo object1 = builder.BuildUp<DataAccess>(locator, null, null);
SingletonPolicyDemo object2 = builder.BuildUp<DataAccess>(locator, null, null);
Trace.WriteLine("Objects equal: " + (object1 == object2));

// Clear locator
locator = new Locator();
locator.Add(typeof(ILifetimeContainer), new LifetimeContainer());

// Disable singleton policy for DataAccess objects
builder.Policies.Set<ISingletonPolicy>(new SingletonPolicy(false), typeof(DataAccess), null);

object1 = builder.BuildUp<DataAccess>(locator, null, null);
object2 = builder.BuildUp<DataAccess>(locator, null, null);
Trace.WriteLine("Objects equal: " + (object1 == object2));

Running this code will show that the singleton pattern is used for the first pair of references, and individual objects are generated for the second pair.  The locator object contains weak references to the objects that are created, and when the singleton policy is in effect this is searched to see if this object has already been created.  However since only weak references are used, we need to create a LifetimeContainer to maintain strong references to the created objects and prevent them from being garbage collected.

Comments

  • Anonymous
    September 26, 2007
    Important: keep a strong reference to the LifetimeContainer instance! Otherwise, it will get garbage collected in an uncontrolled fashion, and all the singletons along with it. Thus, the code above should read: // a variable that has the same scope as locator and builder ILifetimeContainer lifetimeContainer = new LifetimeContainer(); // We need a lifetime container to keep references to the objects // SingletonStrategy depends on this! locator.Add(typeof(ILifetimeContainer), lifetimeContainer);