Dependency Injection - a Small StructureMap Example

Here is the smallest possible example of using StructureMap 2.6.1 (download here) to do Dependency Injection.

Notice how on the line "ObjectFactory.GetInstance<Account>();" that StructureMap will create an account object and see that it needs an "ICustomer" object in its constructor and put a "Customer" object in its constructor for us.

using System;
using NBehave.Spec.NUnit;
using StructureMap;

namespace StructureMapTest {
    public interface ICustomer { string GetName(); }
    public class Customer : ICustomer
    {
        public string GetName(){return "T. Boone Pickens";}
        public override string ToString() {return GetName();}
    }
    public class Account
    {
        public ICustomer MyCustomer { get; set;}
        public Account(ICustomer customer) {
            MyCustomer = customer;
        }
    }
    class StructureMapRunner {
        static void Main() {
            ObjectFactory.Initialize(x => x.For<ICustomer>().Use<Customer>));
            Account account = ObjectFactory.GetInstance<Account>();
            account.MyCustomer.GetName().ShouldEqual("T. Boone Pickens");
        }
    }
}