Software Mechanics
Why do we even have that lever?

Deconstructing ObjectBuilder - What Is ObjectBuilder?

January 25, 2008 17:12 by Chris

Dependency Injection and confusion

ObjectBuilder is most often described as a Dependency Injection (DI)  tool. But looking at the code doesn't really reveal much in the way of how to use this thing to do dependency injection. Instead, you get almost immediately swamped in locators, strategies, builders, and what's that build key supposed to be anyway?

have also heard ObjectBuilder described as "A framework to build dependency injection containers." This is both inaccurate and scary; we have to build something on top of this thing to get the promised dependency injection goodness? If ObjectBuilder is all about DI, why doesn't it actually do it?

The shipping parts in ObjectBuilder do actually implement a reasonable version of DI once you figure out how to assemble everything. Figuring out how to assemble the parts unfortunately requires reading the OB code. And if you read the code with DI in mind, you'll find yourself lost very quickly (I sure did).

he reason for this confusion comes from a basic misunderstanding of what OB actually does. OB is not a DI container. It's also not a DI container framework. ObjectBuilder is actually a configurable object factory.

Object Factories

So what does that mean? The concept of an object factory is fairly straightforward: it's something that you ask for an instance of some type, and it gives you one. The Gang of Four's Design Patterns book includes three different patterns that involve a factory object: Abstract Factory defines an entire class to create instances of a set of objects, Builder encapsulates the details of constructing a set of objects, and Factory Method defines a method you call to get your objects.

At first glance, the factory is an underappreciated concept. Why not just call new instead? The fundamental reason is coupling. When you call new, you hard code the concrete type you'll be creating. For example: 

    public decimal CalculateTaxes(Citizen citizen)
    {
        FederalTaxCalculator taxCalculator = new FederalTaxCalculator();
        return taxCalculator.CalculateTaxFor(citizen);
    }

This code is just fine, except - what happens when marketing decides that we should also support taxes for states as well? Do we do this:

    public decimal CalculateTaxes(Citizen citizen)
    {
        WashingtonAndFederalTaxCalculator taxCalculator = new WashingtonAndFederalTaxCalculator();
        return taxCalculator.CalculateTaxFor(citizen);
    }

That's great for Washington customers, but now we need to maintain 50 separate versions of the software, one for each state. This is typically where we define an interface to define the commonality between the calculator objects.

    public interface ITaxCalculator
    {
        decimal CalculateTaxFor(Citizen citizen);
    }

This now lets us write our CalculateTaxes methods in terms of the interface:

    public decimal CalculateTaxes(Citizen citizen)
    {
        ITaxCalculator calculator = new FederalTaxCalculator();
        return calculator.CalculateTaxFor(citizen);
    }

Unfortunately, this interface didn't actually buy us anything. The problem is the call to new. We've hard coded the concrete type in there, which means we're stuck with creating separate versions. This is the point where a factory gets introduced. For example, using an Abstract Factory object:

    public decimal CalculateTaxes(Citizen citizen)
    {
        TaxCalculatorFactory factory = new TaxCalculatorFactory();
        ITaxCalculator calculator = factory.CreateCalculator();
        return calculator.CalculateTaxFor(citizen);
    }

The TaxCalculatorFactory object encapsulates all the details of figuring out which tax calculator object to create. It could use any method desired to figure out what concrete class to create, but our client code neither knows nor cares about the details.

In modern systems, you'll often find yourself writing small, custom factory classes like this. This is exactly what happened in p&p during the development of Enterprise Library and CAB. The repetition of writing this stuff resulted in ObjectBuilder.

ObjectBuilder - The Generic Factory

ObjectBuilder is a library that lets you set up object factories in a highly configurable way. Using OB uses several classes together:
  • Builder: A Builder object is the actual factory object you call into, but it doesn't actually do the creation work, but it doesn't actually create the objects. Instead, it sets up the rest of the factory, and calls into a Strategy Chain.
  • Strategy Chain: An ordered collection of strategy objects. The Strategy Chain makes sure that the strategies run in the correct order.
  • Strategy: A class that performs one part of the construction process.
  • Policy: Policy objects are used by strategies to communicate down the chain with other strategies, and to provide customization of the strategy's actions.
That was pretty abstract, so let's build a simple example.

A Roundabout Way to Create Objects

Let's start by assembling a simple factory that'll create objects of a requested type for us.

The Entry Point

The entry point to an OB based factory is the IBuilder interface:

    public interface IBuilder
    {
        object BuildUp(IReadWriteLocator locator,
            ILifetimeContainer lifetime,
            IPolicyList policies,
            IStrategyChain strategies,
            object buildKey,
            object existing);

        TTypeToBuild BuildUp<TTypeToBuild>(IReadWriteLocator locator,
            ILifetimeContainer lifetime,
            IPolicyList policies,
            IStrategyChain strategies,
            object buildKey,
            object existing);

        TItem TearDown<TItem>(IReadWriteLocator locator,
            ILifetimeContainer lifetime,
            IPolicyList policies,
            IStrategyChain strategies,
            TItem item);
}


The method of interest here is the BuildUp method. This is the one that you call to actually initiate the construction of an object. A builder has a list of Policy objects and a list of Strategy object that it uses to actually perform the creation of the object. There are a lot of details in this small interface; we'll hit them all as we go through the tutorial. For now, please allow me to gloss over the specifics for the moment. We'll get back to them, I promise.


There is an implementation of this interface called, imaginatively enough, Builder, that ships with the ObjectBuilder library. This class provides a straightforward implementation of the interface, but there are a lot of separate things you have to manage to call BuildUp. So, we'll create our own factory class that wraps the underlying Builder object and manages these extra parts.

Let's create a simple test that demonstrates how we want our new factory to behave. The simplest use is to create an object without any parameters:

        [TestMethod]
        public void ShouldCreateObjectGivenRuntimeType()
        {
            BasicFactory factory = new BasicFactory();
            object result = factory.Create(typeof (Customer));
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(Customer));
        }

    class Customer
    {
        private string firstName;
        private string lastName;


        public Customer()
        {
        }

        public Customer(string firstName, string lastName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }

        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }
    }

Our BasicFactory class will have one method, Create, that takes a Type object indicating which type to create. So, let's implement IBuilder.

Luckily, there's a base class already in the library, BuilderBase, which takes care of the vast majority of the details when implementing IBuilder. So we'll inherit from that. Our first cut at the BasicFactory looks like this:

public class BasicFactory : BuilderBase<BuilderStage>
{
    public object Create(Type t)
    {
        return null;
    }
}

This is just to get the test to compile, but obviously it doesn't pass. Let's implement that Create method now.

Invoking the Builder

Remember that BuildUp method above? This is the "real" method that actually kicks off the ObjectBuilder process. So, all we need to do (all? Hah!) is create a Builder instance and call BuildUp. Unfortunately, BuildUp has several parameters. We can safely pass null for the IReadWriteLocator and ILifetimeContainer, so we'll do that for now (I'll talk about what these objects do in a future installment). But one thing we really need is a StrategyChain, with a strategy in it. So let's build one.

Creating the BasicCreationStrategy

Strategy objects do the actual work in ObjectBuilder. The Builder class simply invokes a set of strategies. Strategies implement the IBuilderStrategy interface:

    public interface IBuilderStrategy
    {
        object BuildUp(IBuilderContext context,
                       object buildKey,
                       object existing);

        object TearDown(IBuilderContext context,
                        object item);
    }

Only two methods, so not too complicated. BuildUp is called when the strategy is invoked during a call to IBuilder.BuildUp. TearDown is called when ObjectBuilder is being used to manage object lifetime, and the object is going away (more about this in later installments).


The parameters to BuildUp are:

  • IBuilderContext: This contains information about the current build operation. The context allows access to the current policy set, and the current set of strategies being executed.
  • object buildKey: The build key object provides information about the type that's currently being built. It can just be a Type object (which is what we'll use here), but can be another object containing additional information if you need it. (More about this later).
  • object existing: A call to BuildUp might pass in an object that's already been created, or an earlier strategy might have created and object and then passed it down the chain for later work.

The ObjectBuilder code includes an implementation of IBuilderStrategy called, amazingly enough, BuilderStrategy. This base class is, in practice, used to implement strategy objects rather than implementing the interface directly. 

Our BasicCreationStrategy looks like this:

public class BasicCreationStrategy : BuilderStrategy
{
    public override object BuildUp(IBuilderContext context, object buildKey, object existing)
    {
        object result = existing;
        if(result == null)
        {
            Type typeToBuild = BuilderStrategy.GetTypeFromBuildKey(buildKey);
            result = Activator.CreateInstance(typeToBuild);
        }
        return base.BuildUp(context, buildKey, result);
    }
}

Fundamentally, this is just a call to Activator.CreateInstance. However, it's slightly more complicated because I want a well behaved strategy class.  Strategies are invoked in a chain. We want to make sure we don't destroy any work done by a previous strategy, so we make sure that we don't create a new instance if we already have one. And afterward, we want to pass our created instance to the next strategy in the chain, so we call the base class's implemention of BuildUp, which invokes the rest of the strategy chain for us.

Inserting the Strategy and Builder Stages

So now I have my strategy. I need to insert it into a strategy chain. Since I always want BasicFactory to use this strategy, it's easiest to simply add it in a constructor:

public class BasicFactory
{
    StagedStrategyChain<BuilderStage> strategies = new StagedStrategyChain<BuilderStage>();
    public BasicFactory()
    {
        strategies.AddNew<BasicCreationStrategy>(BuilderStage.Creation);
    }
...

The call to strategies.AddNew creates a new instance of our BasicCreationStrategy class. The parameter, BuilderStage.Creation, is kind of interesting here. Did you notice in the definition of the strategies variable above, that the StagedStrategyChain has a generic type parameter? This type parameter defines the builder Stages, and is typically an enum (it could be an int if you want). Each strategy is in one and only one stage. The strategies are executed in order that the stages are defined. OB ships with the BuilderStage enum, which makes an excellent default. It defines the following stages: PreCreation, Creation, Initialization, and PostInitialization. All strategies placed in the PreCreation stage execute first, followed by the strategies in the Creation stage, and so on. Within a stage, the strategies execute in the order they were added. Stages aren't strictly necessary, but they do provide users of a builder the option to add extra strategies at various points in the chain.

Let's put the entire class together and implement the Create method:

public class BasicFactory
{
    private StagedStrategyChain<BuilderStage> strategies = new StagedStrategyChain<BuilderStage>();
    private PolicyList policies = new PolicyList();

    public BasicFactory()
    {
        strategies.AddNew<BasicCreationStrategy>(BuilderStage.Creation);
    }

    public object Create(Type t)
    {
        Builder builder = new Builder();
        return builder.BuildUp(
            null,
            null,
            policies,
            strategies.MakeStrategyChain(),
            null);
    }
}

In our case, we only have the one strategy, and the Creation stage seems to be the appropriate place to put it. If we now run our test, it passes!

Using Policies to Pass Information

So, we now have a factory that can create an object of any type we pass to it. Except - what about object that take constructor parameters? My little Customer object has a constructor that lets you set the first and last name. Let's write another test that shows that we can pass parameters to the Create method:

        [TestMethod]
        public void ShouldCreateObjectWithParameters()
        {
            BasicFactory factory = new BasicFactory();
            object result = factory.Create(typeof (Customer), "John", "Doe");
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof (Customer));
            Customer c = (Customer) result;
            Assert.AreEqual("John", c.FirstName);
            Assert.AreEqual("Doe", c.LastName);
        }
Getting this to compile requires a slight tweak to the definition of the Create method. Specifically, passing in the arguments:

    public object Create(Type t, params object[] constructorArgs)
    {
        Builder builder = new Builder();
        return builder.BuildUp( null, null,
            policies,
            strategies.MakeStrategyChain,
            t,
            null);
    }

Now we have a bit of a problem. Although we've added the constructor arguments to our Create method, looking at the signature of BuildUp, there's nowhere to put them. So how do we get the parameters into the call, so that the strategy can take advantage of them?

If we look at the definition of BuildUp, the first parameter is a locator object. This is one possibility: the locator lets strategies look up objects via an arbitrary key. However, locators in general are intended to be used to store information that lasts longer than a single call to BuildUp. Since the parameters are only used in this one call, the locator isn't really appropriate.

So, we need to put the parameters somewhere else. That somewhere else is a Policy object.

Policies provide an "out of band" mechanism for strategies to get extra information. In our case, we need to store away the constructor parameters someplace that the strategy can find later.

 
It's generally a good idea to provide an interface that defines the contract of your policy, so that you can provide multiple implementations later. So, I started with this interface:

public interface ICreationParameterPolicy : IBuilderPolicy
{
    object[] Parameters { get; }
}

Policy interfaces derive from IBuilderPolicy. IBuilderPolicy doesn't actually have any methods; it's used as a marker interface to tell the OB plumbing that this is, indeed a policy object.

So we have an interface that lets us retrieve the constructor parameters. Let's implement it:

public class CreationParameterPolicy : ICreationParameterPolicy
{
    private object[] parameters;

    public CreationParameterPolicy(params object[] parameters)
    {
        this.parameters = parameters;
    }

    public object[] Parameters
    {
        get { return parameters; }
    }
}

We have a fairly trivial data-holder object here. Next up, we need to use this policy in our strategy object. Policies are looked up via a method on the builder context object passed to BuildUp. The new implementation of our strategy is:

    public override object BuildUp(IBuilderContext context, object buildKey, object existing)
    {
        object result = existing;
        if(result == null) {
            Type typeToBuild = BuilderStrategy.GetTypeFromBuildKey(buildKey);
            ICreationParameterPolicy policy =
                context.Policies.Get<ICreationParameterPolicy>(buildKey);
            if (policy != null) {
                result = Activator.CreateInstance(typeToBuild, policy.Parameters);
            } else {
                result = Activator.CreateInstance(typeToBuild);
            }
        }
        return base.BuildUp(context, typeToBuild, result, idToBuild);
    }

The lookup of the policy occurs at the call to context.Policies.Get. It takes one generic type parameter, the type of policy to retrieve, and a key to look up the specific policy. As seen here, typically you'll use the build key as the parameter to look up your policy.

If we have the policy object in our context, we then pass the results of calling policy.Parameters to Activator.CreateInstance, and voila! We have construction with parameters. Unfortunately, if you run our test and debug through, we don't actually have the policy object. So how do you get the policy object into the context?

If we go back and look at the signature of IBuilder.BuildUp:

        object BuildUp(IReadWriteLocator locator,
            ILifetimeContainer lifetime,
            IPolicyList policies,
            IStrategyChain strategies,
            object buildKey,
            object existing);

Take a look at that third parameter. The policy list is passed into the BuildUp call. We already have a policy list as a member variable of our factory class, so we could just stick it in there. But that's not quite what we want. Remember, this particular policy should only be used for the current BuildUp call. If we put it in the member variable, it'll stick aroudn across calls (unless we explicitly remove it). Luckily, the PolicyList class supports a hierarchy. When you create a PolicyList, you can specify a parent. If a lookup in the current PolicyList fails, it'll try its parent. This gives us the ability to have persistent and transient policies. Persistent policies are added to the member variable in the factory itself (much like strategies are), and are available every time the builder object is used. Transient policies, on the other hand, are only available for the lifetime of a single call to BuildUp. In this case, we only want the constructor parameters to be available for the construction of this single object, since they'll change on every call to the builder. So, we'll add a transient policy. The new implementation of BasicFactory.Create looks like this:

    public object Create(Type t, params object[] constructorArgs)
    {
        Builder builder = new Builder();
        PolicyList transientPolicies = new PolicyList(policies);
        transientPolicies.Set<ICreationParameterPolicy>(new CreationParameterPolicy(constructorArgs), t);
        return builder.BuildUp( null, null,
            transientPolicies,
            strategies.MakeStrategyChain(),
            t,
            null);
    }

We create a new PolicyList object, and then we add a new CreationParameterPolicy to it. Notice the Set call takes one type parameter and two regular parameters: the type of the policy, the policy object instance, and key to use (the type of object we're creating in this case). This corresponds to the Get call in our strategy above. Finally, we pass this new PolicyList to base.BuildUp, and our policy is now available to our strategy. The test passes.

Where Are We?

So far, we've written three classes and an interface to reproduce the effect of a single-line call to Activator.CreateInstance. Using ObjectBuilder doesn't really make sense for this particular usage, but along the way we've hit many of the "moving parts" of the ObjectBuilder framework that will serve us well later:

  • A Builder object maintains a chain of Strategy objects, and invokes them in order when requested.
  • Strategies provide the actual logic used in the creation process.
  • Policies provide additional "out of band" logic, and are looked up based on a policy type and key.

Next time, let's look at how we can combine strategies to provide more than just a big wrapper around a call to new.


Currently rated 5.0 by 10 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Comments are closed