Demystifying the ObjectBuilder
In my last post, I gave an introduction to ObjectBuilder. In this post, I take ObjectBuilder apart and talk about all of the hairy details.
ObjectBuilder is used in the Enterprise Library, the CAB, and the Mobile framework MS just released. If you have to extend any of the above frameworks/libraries in a non-trivial way, you are going to need to understand what is going on under the covers. Under the covers of the above frameworks/libraries is ObjectBuilder--the dependency injection framework.
Unfortunately, there is not any documentation for the ObjectBuilder, so learning is a real nightmare. I was able to break it by going over the unittests that ship with the source code.
Fundamental Classes in Object Builder
Strategy and Policies - OB is based upon policies and strategies. Strategies are chained (i.e. OB implements the Chain of Responsability pattern on strategies) and get registered for a build stage. Strategies use policies to figure out how to build an object. Policies are registered with OB for types. A policy is defined for types (objects in OB are defined by the type and ID).
Locator - locators in OB are used to find registered objects. When an object is created, it gets registered with the locator (see CreationStrategy.RegisterObject).
LifetimeContainer - objects managed by the object builder can have a lifetime associated with them. The thing that determines how long an object stays around is the container that the object is associated with. LifetimeContainers in OB, maintain a list of objects. When the container is disposed off, the objects in it are also disposed.
BuilderContext- an object that defines the context for the build-up and tear-down of an object. BuilderContext holds the strategies, policies and locator for the given build-up or tear-down. It also provides a method to iterate the chain of strategies (see IBuilderContext and BuilderContext).
OB By Example
/**********Create A Singleton*************/
public void CreateASingleton()
{
// we need a locator, a strategy chain, and a list of policies.
Locator locator = new Locator();
BuilderStrategyChain strategyChain = new BuilderStrategyChain();
PolicyList policies = new PolicyList();
// in order to build a singleton, we have to
// have a SingletonStrategy. The singleton strategy
// in turn uses a SingletonPolicy.
// add a SingletonStrategy to the strategy chain
strategyChain.Add(new SingletonStrategy());
// add a CreationStrategy to the strategy chain
strategyChain.Add(new CreationStrategy());
// SingletonStrategy requires a SingletonPolicy
policies.Set<ISingletonPolicy>(new SingletonPolicy(true), typeof(MyObject), null);
// we also need a creation policy
policies.SetDefault<ICreationPolicy>(new DefaultCreationPolicy());
// in order to make singletons, we need a lifetime container in the locator
locator.Add(typeof(ILifetimeContainer), new LifetimeContainer());
// create the object
BuilderContext cxt = new BuilderContext(strategyChain, locator, policies);
// in order to properly track singletons, we have to give the instance an ID.
object myObj = strategyChain.Head.BuildUp(cxt, typeof(MyObject), "MyObject_Singleton", null);
object myObj2 = strategyChain.Head.BuildUp(cxt, typeof(MyObject), "MyObject_Singleton", null);
if (myObj == myObj2)
{
// Got singleton in myObj2
int J = 0;
}
}
The example above demonstrates creating singleton objects with the OB. Most of the work simply sets up using the OB. For example, in order to create an object, we need to have a build context. A build context requires a locator, a strategy chain, and a policy list. There are several pieces that enable singletons, however. For example, utimately a strategy is the thing that will create an object in OB. Strategies rely on policies to determine how to create an object. To create a singleton, we have to have a SingletonStrategy in the strategy chain. The singleton strategy looks for a SingletonPolicy, registered for the object being created. Recall that policies are setup for types.
There are a few design aspects of OB that we have to understand. OB uses something called a Locator. A locator knows how to find registered objects. Locators can be nested (i.e., a locator can have a parent). Locators make use of something called a LifetimeContainer. LifetimeContainer puts a boundary around the lifetime of a created object. When a locator is asked to find an object it can look in the current locator and/or it's parent locator (if one exists).
It's important to know that when searching for singletons, OB looks only at the current locator--the parent is not searched. The SingletonStrategy class in OB is shown below for reinforcement of this.
public class SingletonStrategy : BuilderStrategy
{
public override object BuildUp(IBuilderContext context, Type typeToBuild, object existing, string idToBuild)
{
DependencyResolutionLocatorKey key = new DependencyResolutionLocatorKey(typeToBuild, idToBuild);
if (context.Locator != null && context.Locator.Contains(key, SearchMode.Local))
{
TraceBuildUp(context, typeToBuild, idToBuild, "");
return context.Locator.Get(key);
}
return base.BuildUp(context, typeToBuild, existing, idToBuild);
}
}
As shown, the SingletonStrategy checks to see if the build context has a locator,and then asks the locator to find the object using a SearchMode.Local. This tells the locator not to look in the parent locator for the object. This has obvious usage implications--if you don't create your singletons with the correct locator, then you'll end up breaking the singleton (TODO: more on this.).
Also note that we have put a CreationStrategy in the chain of strategies for our singleton object. The SingletonStrategy ensures that once we have an object, that object is returned on subseqent build-up requests. The CreationStrategy is needed to build-up the object the first time. Since the CreationStrategy is the strategy that builds the object, this strategy also registers the object with the locator/container so that it can be pulled out the next time. We can see this by looking at the CreationStrategy.
public class CreationStrategy : BuilderStrategy
{
public override object BuildUp(IBuilderContext context, Type typeToBuild, object existing, string idToBuild)
{
if (existing != null)
BuildUpExistingObject(context, typeToBuild, existing, idToBuild);
else
existing = BuildUpNewObject(context, typeToBuild, existing, idToBuild);
return base.BuildUp(context, typeToBuild, existing, idToBuild);
}
private void BuildUpExistingObject(IBuilderContext context, Type typeToBuild, object existing, string idToBuild)
{
RegisterObject(context, typeToBuild, existing, idToBuild);
}
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.SerializationFormatter)]
private object BuildUpNewObject(IBuilderContext context, Type typeToBuild, object existing, string idToBuild)
{
ICreationPolicy policy = context.Policies.Get<ICreationPolicy>(typeToBuild, idToBuild);
if (policy == null)
{
if (idToBuild == null)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
Properties.Resources.MissingPolicyUnnamed, typeToBuild));
else
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
Properties.Resources.MissingPolicyNamed, typeToBuild, idToBuild));
}
try
{
existing = FormatterServices.GetSafeUninitializedObject(typeToBuild);
}
catch (MemberAccessException exception)
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Properties.Resources.CannotCreateInstanceOfType, typeToBuild), exception);
}
RegisterObject(context, typeToBuild, existing, idToBuild);
InitializeObject(context, existing, idToBuild, policy);
return existing;
}
private void RegisterObject(IBuilderContext context, Type typeToBuild, object existing, string idToBuild)
{
if (context.Locator != null)
{
ILifetimeContainer lifetime = context.Locator.Get<ILifetimeContainer>(typeof(ILifetimeContainer), SearchMode.Local);
if (lifetime != null)
{
ISingletonPolicy singletonPolicy = context.Policies.Get<ISingletonPolicy>(typeToBuild, idToBuild);
if (singletonPolicy != null && singletonPolicy.IsSingleton)
{
context.Locator.Add(new DependencyResolutionLocatorKey(typeToBuild, idToBuild), existing);
lifetime.Add(existing);
if (TraceEnabled(context))
TraceBuildUp(context, typeToBuild, idToBuild, Properties.Resources.SingletonRegistered);
}
}
}
}
//...more methods ....
}
As shown above, the BuildUp method checks to see if it has to build-up a new object or an existing one. In our case, we are building up an object for the firsttime. In this case, the BuildUpNewObject method is called. This method looks on the build context for a ICreationPolicy for the required object. If it doesn't find one, it throws an exception--in other words, you have to have a policy registered for the object that tells OB how to create the object. In our case, we are using the DefaultCreationPolicy. If there is a ICreationPolicy, then the method builds a bare-bones object (one that is not initialized) using
existing = FormatterServices.GetSafeUninitializedObject(typeToBuild);
and then calls RegisterObject(). This is where the singleton magic happens. As you can see from the code snippet above, the CreationStrategy looks for a lifetime container on the local locator and if one exists, it looks for a singleton policy registered for the required object. If it finds the singleton policy, it adds a key for the newly build object to the lifetime container.
Thus, we can conclude that in order to create singleton objects with OB, we need to have a SingletonStrategy and a SingletonPolicy. There are two aspects to creating a singleton:
- When creating an object, you have to register it.
- When creating an object, you have to check to see if one already exists.
The singleton policy, ensures that the object gets registered with the local locator's lifetime container and the singleton strategy ensures that the registered object gets returned on subsequent build-up operations.
OB is a glorified object factory and DI framework. To support DI, OB ships with some strategies and policies. Lets investigate these now. [TODO: Correct this intro into DI via Properties]
Injecting into Properties
DI in OB is achived at build-up. When you ask OB to build-up an object, OB runs a chain of strategies. The idea is to inject dependencies into objects at build-up. To do that, you put a strategy object, an object that knows how to do the proper injection, into the chain of strategies. One of the strategies that knows how to inject dependencies is the PropertySetterStrategy. An example will help.
public void PropertyInjectionExample()
{
Locator locator = new Locator();
LifetimeContainer container = new LifetimeContainer();
locator.Add(typeof(ILifetimeContainer), container);
// strategies ...
BuilderStrategyChain chain = new BuilderStrategyChain();
chain.Add(new CreationStrategy());
chain.Add(new PropertySetterStrategy());
// policies...
PolicyList policies = new PolicyList();
// Property setter policy for MyDAOObject's ConnectionString
PropertySetterPolicy psp = new PropertySetterPolicy();
// add a property for the ConnectionString property
psp.Properties.Add("ConnectionString", new PropertySetterInfo("ConnectionString",new ValueParameter<string>("the connection string value would be here")));
policies.Set<IPropertySetterPolicy>(psp, typeof(MyDAOObject), null);
policies.SetDefault<ICreationPolicy>(new DefaultCreationPolicy());
// create build conetxt...
BuilderContext cxt = new BuilderContext(chain, locator, policies);
// build the object
MyDAOObject obj = chain.Head.BuildUp(cxt, typeof(MyDAOObject), null, null) as MyDAOObject;
}
class MyDAOObject
{
private string connectionString;
public string ConnectionString
{
get
{
return connectionString;
}
set
{
connectionString = value;
}
}
public MyDAOObject():this(null) { }
public MyDAOObject(string conStr)
{
connectionString = conStr;
}
}
In our introduction, we mentioned that DI is achieved by injecting dependencies into properties or via constructors. The PropertySetterStrategy, as the name suggests, injects dependencies using properties. In order to get properties injected into your objects, you have to add a PropertySetterStrategy instance to the strategy chain (as shown above). The BuildUp method of this strategy is shown below.
public override object BuildUp(IBuilderContext context, Type typeToBuild, object existing, string idToBuild)
{
if (existing != null)
InjectProperties(context, existing, idToBuild);
return base.BuildUp(context, typeToBuild, existing, idToBuild);
}
As you can see, the BuildUp method ensures that the object has been created and then it calls the InjectProperties method. Note the implication here--you have to make sure you have a strategy that creates the object ahead of the PropertySetterStrategy in the strategy chain. Otherwise, the strategy is effectively skipped because the base class's BuildUp is called to call the next strategy in the chain. Now lets have a look at the InjectProperties method (see below).
private void InjectProperties(IBuilderContext context, object obj, string id)
{
if (obj == null)
return;
Type type = obj.GetType();
IPropertySetterPolicy policy = context.Policies.Get<IPropertySetterPolicy>(type, id);
if (policy == null)
return;
foreach (IPropertySetterInfo propSetterInfo in policy.Properties.Values)
{
PropertyInfo propInfo = propSetterInfo.SelectProperty(context, type, id);
if (propInfo != null)
{
if (propInfo.CanWrite)
{
object value = propSetterInfo.GetValue(context, type, id, propInfo);
if( value != null )
Guard.TypeIsAssignableFromType(propInfo.PropertyType, value.GetType(), obj.GetType());
if (TraceEnabled(context))
TraceBuildUp(context, type, id, Properties.Resources.CallingProperty, propInfo.Name, propInfo.PropertyType.Name);
propInfo.SetValue(obj, value, null);
}
else
{
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture,
Properties.Resources.CannotInjectReadOnlyProperty,
type, propInfo.Name));
}
}
}
}
The InjectProperties method checks to see if an object exists and then looks for an implementation of IPropertySetterPolicy registered for the type. If it finds an IPropertySetterPolicy for the type, it iterates over the list properties that need to be injected. The list of properties that need to be injected and the values that need to be injected into these properties are defined by IPropertySetterPolicy.
public interface IPropertySetterPolicy : IBuilderPolicy
{
Dictionary<string, IPropertySetterInfo> Properties { get; }
}
Every property that needs to be injected has to have an entry into this dictionary. Every property has a string key and an IPropertySetterInfo instance that defines the property and the value for that property. Therefore, in our example above, when we create the PropertySetterPolicy for MyObject, we added the following for the ConnectionString property.
psp.Properties.Add("ConnectionString", new PropertySetterInfo("ConnectionString",new ValueParameter<string>("the connection string value would be here")));
The Add method adds an entry with the key "ConnectionString" and a new PropertySetterInfo for the ConnectionString property. If we go back to the InjectProperties method, we can see that the method iterates over the list of IPropertySetterInfo objects. For each property configured for injection, it calls the SelectProperty method on the IPropertySetterInfo object. The default implementation of this interface (PropertySetterInfo) looks at the type to see if it has a property with given name and if it finds one, it returns a PropertyInfo for that type. Note that when we created the PropertySetterInfo object for the property, we gave it the name of the property along with the ValueParameter instance in the constructor of PropertySetterInfo. The IPropertySetterInfo interface defines the SelectProperty method, mentioned above, and the GetValue method (see below). The GetValue method returns the value that has to be injected into the property.
public interface IPropertySetterInfo
{
object GetValue(IBuilderContext context, Type type, string id, PropertyInfo propInfo);
PropertyInfo SelectProperty(IBuilderContext context, Type type, string id);
}
After the InjectProperty method gets the PropertyInfo object for the property, it checks to see if the property can be written to (i.e., if it has a setter), and then calls the GetValue method on the IPropertySetterInfo implementation. The default implementation of this interface calls the GetValue method on the IParameter. In our example, we passed in an ValueParameter instance, which is an implementation of IParameter that stores the value in the class and returns it when needed. Once the value for the property is obtained, the InjectProperties method checks to make sure that the value of the property can be assigned to the property and then it calls PropertyInfo.SetValue.
That's the details on DI via properties. With this much detail, it is easy to lose focus on the big picture, so lets understand the design of this aspect of the OB. The figure below dipicts the design of DI via properties in OB.

As shown, there are really three core interfaces involved in the design, IPropertySetterPolicy, IPropertySetterStrategy, and IPropertySetterInfo. The strategy class looks for a registered IPropertySetterPolicy at build-up for a given type. If the policy is registered for the type, the strategy iterates the properties that require injection. Every injection property is represented by an IPropertySetterInfo. IPropertySetterInfo encapsulates two things about the property: what the property is and how to get a value for the property. OB provides an implementation of this interface, PropertySetterInfo, that operates on an IParameter abstraction (see PropertySetterInfo class below).
public class PropertySetterInfo : IPropertySetterInfo
{
string name = null;
PropertyInfo prop = null;
IParameter value = null;
public PropertySetterInfo(string name, IParameter value)
{
this.name = name;
this.value = value;
}
public PropertySetterInfo(PropertyInfo propInfo, IParameter value)
{
this.prop = propInfo;
this.value = value;
}
public PropertyInfo SelectProperty(IBuilderContext context, Type type, string id)
{
if (prop != null)
return prop;
return type.GetProperty(name);
}
public object GetValue(IBuilderContext context, Type type, string id, PropertyInfo propInfo)
{
return value.GetValue(context);
}
}
As shown, at a minimum, you need to know two things to get a value injected into a property: 1) the name of the property and 2) how to get the value for the property. IParameter provides an abstraction to obtaining, and customizing, how the PropertySetterStrategy obtains the value to assign to the property. In our example earlier, for example, we used a ValueParameter extension that stored the value of the ConnectionString in the class and returned it when the strategy asked for it. The design of DI via properties also shows that OB provides a number of other IParameter extensions. For example, the LookupParameter implement