CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Jeremy D. Miller -- The Shade Tree Developer

Under the hood and working with .Net, TDD, Software Design, and Agile Stuff

StructureMap

  • Before you use an IoC tool, some concepts to know first

     
    JEREMY’s NOTE:  I’m trying to rewrite the StructureMap documentation today, and I’m going to blog most of it out here as I finish it until Brendan tells me to stop polluting the main feed.  This article is intended to be an introduction to the concepts behind an IoC tool for folks with little or no previous exposure.  Feedback will be very much appreciated.
     
     
    From my original release back in June 2004:  StructureMap is a Inversion of Control (IoC) slash Dependency Injection framework that can be used to improve the architectural qualities of an object oriented system by reducing the mechanical costs of good design techniques.  Using StructureMap does not in any way improve your architecture per se, it simply strives to make the mechanics of a good Object Oriented Design cheaper to implement.  Additionally, StructureMap allows you to efficiently exploit a well designed Object Oriented architecture to provide extensibility mechanisms, flexible deployment options, and self validating configuration and deployment.

    Over the years a series of concepts and principles have been discovered and developed to describe well-structured Object Oriented systems.  To most effectively use StructureMap, or any other IoC tool for that matter, your system needs to be designed with these principles first:

    To sum it all up, well designed Object Oriented systems are composed of many objects that work with each other to accomplish to goals of the system.  We want our systems to be decomposed into cohesive classes that perform a well defined responsibility within the system, rather than monolithic “God” classes that do too much.  A cohesive class will have to be dependent upon other classes to perform services outside of its own tightly defined responsibility.  In IoC speak, we call the collaborating objects dependencies

     

    Dependencies

    For example, in my current system we have a class called AddressEditController that governs the creation and editing of Address entities in our web based UI.  The AddressEditController needs to validate user input and persist or load data.  Those are two distinct responsibilities, so AddressEditController has dependencies on other objects for these services. 

        public class AddressEditController : Controller

        {

            // AddressEditController uses IValidator to validate user input

            // and IRepository to load and save Address information

            private readonly IValidator _validator;

            private IRepository _repository;

     

        }

    So here’s some facts about AddressEditController:

    • AddressEditController depends on IValidator and IRepository 
    • AddressEditController cannot function unless it has both an IValidator and an IRepository
    • From the concepts section above, for best results, the AddressEditController should be loosely coupled to its dependencies by knowing as little about the inner workings of the real IValidator and IRepository
    • The real IRepository is a Gateway into NHibernate. The concrete Repository class cannot be used without its own dependency trail of external configuration, a Singleton to keep track of an expensive resource, and some NHibernate bootstrapping code. 

    Just calling a new() constructor on its dependencies isn’t the best design for our AddressEditController.  Creating a concrete Validator class is very possible, but what if we want to selectively replace the implementation of IValidator later?  That’s only somewhat likely, but the dependency on Repository is a much larger concern.  I might have semantic decoupling between AddressEditController and Repository, but if AddressEditController calls new Repository() itself, AddressEditController will not be able to function without all that NHibernate bootstrapping.  I do not want a piece of my user interface to be tightly coupled to the existence of the persistence layer. 

    In other scenarios, creating the dependencies may involve more than just calling new() on the dependencies (don’t believe me?  Go try to create an HttpContext object).

    AddressEditController is responsible for the workflow around editing Address entities in the UI.  It shouldn’t be concerned with NHibernate configuration and whatnot.  One way to solve this problem is to move the responsibility for building its dependencies to somewhere external to AddressEditController

     

    Inversion of Control and Dependency Injection

    In many cases, I don’t want my classes to have to be aware of how their dependencies are created or located.  I don’t want controller classes to even care that they’re using an object that is created via Microsoft’s Provider infrastructure, or a Singleton, or needs configuration data.  My class should only know the public interfaces of its dependencies.  I can make that true by applying “Inversion of Control.”  Instead of doing:

            public AddressEditController()

            {

                _validator = new Validator();

                _repository = new Repository();

            }

    where AddressEditController calls linearly through to the constructors on Validator and Repository, we can invert the control to make the creator of AddressEditController responsible for building the dependencies and “pushing” them into AddressEditController

        public class AddressEditController : Controller

        {

             private readonly IValidator _validator;

            private IRepository _repository;

     

            public AddressEditController(IValidator validator, IRepository repository)

            {

                _validator = validator;

                _repository = repository;

            }

        }

    The code sample above uses a form of Inversion of Control called Dependency Injection to push in the dependencies via a constructor function.  Of course, at some point, something needs to know how to create the entire chain of dependencies and do all of that Dependency Injection.  StructureMap supports a pattern known as Service Locator:

                // Creates an AddressEditController with all of its dependencies

                AddressEditController controller = ObjectFactory.GetInstance<AddressEditController>();

    ObjectFactory is a StructureMap class that serves as a well known place to go and find any service that you need.  When the AddressEditController is created and returned by ObjectFactory, it should be completely ready to go.  There’s another important concept to understand before you use StructureMap. 

     

    Auto Wiring

    Every "real" IoC container supports the concept of "Auto Wiring."  Auto Wiring simply means that StructureMap can figure out dependency chains for you without a lot of explicit configuration.  When you ask for AddressEditController, there is more going on than just AddressEditController and its two dependencies.  The Repository class itself has its own dependencies.

            [DefaultConstructor]

            public Repository(ISessionSource source) : this(source.CreateSession())

            {

     

            }

    In turn, the concrete version of ISessionSource above has its own dependencies:

            public SessionSource(IDictionary<string, string> properties, PersistenceModel model)

            {

                _configuration = new Configuration();

                _configuration.AddProperties(properties);

     

                model.Configure(_configuration);

     

                _sessionFactory = _configuration.BuildSessionFactory();

            }

    which starts to get interesting because SessionSource needs some information like connection strings that have to come in from Xml configuration: 

    <StructureMap MementoStyle="Attribute">

      <DefaultInstance

        PluginType="ShadeTree.DomainModel.ISessionSource,ShadeTree.DomainModel"

        PluggedType="ShadeTree.DomainModel.SessionSource,ShadeTree.DomainModel">

        <properties>

          <Pair Key="connection.provider" Value="NHibernate.Connection.DriverConnectionProvider" />

          <Pair Key="connection.driver_class" Value="NHibernate.Driver.SqlClientDriver" />

          <Pair Key="dialect" Value="NHibernate.Dialect.MsSql2000Dialect" />

          <Pair Key="hibernate.dialect" Value="NHibernate.Dialect.MsSql2000Dialect" />

          <Pair Key="use_outer_join" Value="true" />

          <Pair Key="connection.connection_string" Value="a connection string that I’m certainly not giving out to you!" />

          <Pair Key="show_sql" Value="true" />

        </properties>

      </DefaultInstance>

    </StructureMap>

    Here’s some of the configuration for the other services that the entire EditAddressController needs:

                ForRequestedType<IValidator>().TheDefaultIsConcreteType<Validator>();

                ForRequestedType<IRepository>().TheDefaultIsConcreteType<Repository>().CacheBy(InstanceScope.Hybrid);

                ForRequestedType<PersistenceModel>().TheDefaultIsConcreteType<DovetailPersistenceModel>();

    At no point did I specify that EditAddressController needs an IRepository that needs an ISessionSource that needs 2-3 other things, but yet when I call:

                // Creates an AddressEditController with all of its dependencies

                AddressEditController controller = ObjectFactory.GetInstance<AddressEditController>();

    StructureMap will construct EditAddressController that had a new instance of Repository that had a new instance of SessionSource that had an IDictionary<string, string> object and a new instance of DovetailPersistenceModel.  I don’t have to explicitly tell StructureMap to do that for me because it uses its “Auto Wiring” feature to examine the dependencies of each concrete class and act accordingly.  StructureMap does need to know what to do with each type of object it encounters.  When it tries to build the Repository class StructureMap sees the constructor argument for ISessionSource on Repository, and knows to build and inject a new SessionSource object (and so on as deep as you need to go).

  • StructureMap 2.4.9 Preview Release is available

    A preview release of StructureMap 2.5 is available now at http://sourceforge.net/projects/structuremap.  The code is completely baked (minus some convenience methods I'm going to throw in), but I'm lagging on the documentation (life has been intruding on my side project time lately).  I'll make the full and official release as soon the documentation is done.  This release marks a large scale re-architecture of StructureMap and has taken it very far from its roots as a simple tool to build objects from an Xml representation.  As such, I'm completely rewriting the documentation and website as well.  I'm hoping to include quite a few samples of usage.

    The new functionality in StructureMap 2.5:

    * The ability to use StructureMap with ZERO Xml or attributes by default 

    * The ability to add services at runtime.  You can now programmatically add an entire Assembly at runtime for modular applications that might not want all services to be loaded at startup.

    * An auto mocking container based on Rhino Mocks 3.5.  I was a doubter on the validity of AMC, but I'm sold now that I've used it 

    * More sophisticated auto wiring rules

    * Supporting NameValueCollection and IDictionary<Key, Value> types

    * Far more extensibility

    * Interception and post processing hooks for you AOP enthusiasts.  StructureMap will NOT include its own AOP engine, but will allow you to use the runtime AOP technique of your choice.

    * More configuration options in both Xml and the Fluent Interface.  Usability tweaks for the Fluent Interface.

    * More options for modular configuration (mix and match Xml configuration or Registry's at will) -- which basically had to trigger:

    * Completely revamped diagnostics, including the Environment Testing support

    * Transparent creation of concrete types that are not explicitly registered

    * Create objects with explicit arguments passed to the container

    * Use the underlying Container independently of ObjectFactory

    * Pluggable auto registration

    * StructureMap is now strong named (thanks to Steve Harman)

    * Pull configuration from the App.config (thanks to Josh Flanagan)

    * Generics fixes (thanks to Derrick Rapp) 

     

     

    Anyway, I've got some documentation to go write.... 


  • Working faster and fewer mapping errors with NHibernate

    EDIT:  To access the codebase below, the user name is "guest" and the password is blank.  http://codebetter.com/blogs/jeremy.miller/archive/2008/02/01/access-to-the-storyteller-source-code.aspx

     

     

    Yesterday, David Laribee related some problems he experienced with refactorings in his domain model leading to some breaking problems with NHibernate mappings.  Specifically, the issues are:

    1. Changing the property names of a domain model can break the NHibernate mapping
    2. Changing the database fields can break the NHibernate mappings

    David went on to bemoan the absence of a quick way to validate NHibernate mappings.  Ayende popped in with the suggestion that the presence of integrated tests around the NHibernate usage would spot mapping problems.  Other folks mentioned that there's a new ReSharper plugin to validate and refactor NHibernate mappings.  I'll circle back to the refactoring plugin in a while. 

    First I want to talk about quick ways to validate NHibernate mappings.  Ayende is right of course about the integrated tests against the individual queries, but I'm going to suggest that that isn't the most efficient answer to the question of validating the mappings.  The bigger integration tests will tell you that something is wrong, but from experience they'll be harder to diagnose because there is so much more going on than simple property checking, and they provide a slow feedback cycle because of how much stuff is going on.  What would be nice is a way to walk right up to a mapping and specify which properties on a class are supposed to be persisted and how.

    I thought I would come out of my blogging retirement and show an example of the Chad and Jeremy approach to testing NHibernate mappings:

            
    
            [SetUp]
            public void SetUp()
            {
                // Ensure that the StructureMap configuration is bootstrapped
                // In our case, this includes everything we need setup to 
                // execute NHibernate (mappings + ISessionFactory configuration)
                // This will be pretty application specific here
                Bootstrapper.RestartStructureMap();
            }
            
            [Test]
            public void SaveAndLoadCustomerContact()
            {
                new PersistenceSpecification<CustomerContact>()
                    .CheckProperty(x => x.Name, "Frank")
                    .CheckProperty(x => x.Email, "Email")
                    .CheckProperty(x => x.Extension, 123)
                    .CheckProperty(x => x.FaxNumber, "111-111-1111")
                    .CheckProperty(x => x.TelephoneNumber, "222-222-2222")
                    .CheckProperty(x => x.Title, "Mr.")
                    .VerifyTheMappings();
            }
            

    All this test does is ensure that the 6 properties of the CustomerContact class (Name, Email, Extension, FaxNumber, TelephoneNumber, Title) are mapped in NHibernate.  We have some other methods for checking to many and many to one type relationships. 

    Behind the scenes the PersistenceSpecification<T> class:

    1.  Creates a new instance of T
    2. Uses the lambda expressions and suggested values in the calls to CheckProperty to load values into the new instance of T
    3. Grabs our IRepository out of StructureMap (of course), and saves the object
    4. Grabs a second IRepository out of StructureMap
    5. Fetches a second copy of the same T out of the second IRepository
    6. Verifies that all of the specified properties in the specification were saved and loaded.  If any single property does not match between the first T and the second T, the test will fail.

    Here's the implementation of the PersistenceSpecification.VerifyTheMappings() method:

            public void VerifyTheMappings()
            {
                // Create the initial copy
                var first = new T();
    
                // Set the "suggested" properties, including references
                // to other entities and possibly collections
                _allProperties.ForEach(p => p.SetValue(first));
    
                // Save the first copy
                _repository.Save(first);
    
                // Get a completely different IRepository
                var secondRepository = createRepository();
    
                // "Find" the same entity from the second IRepository
                var second = secondRepository.Find<T>(first.Id);
    
                // Validate that each specified property and value
                // made the round trip
                // It's a bit naive right now because it fails on the first failure
                _allProperties.ForEach(p => p.CheckValue(second));
            }
        

    The advantage of this testing is that it gives a (relatively) fast feedback cycle focused specifically on the mappings.  Tools that check the hbm.xml mappings can only verify that what's there is correctly formed.  The mapping tests above will catch missing mappings and desired behavior.  At a bare minimum, you really should have at least one smoke test in your CI build that simply tries to create an NHibernate ISession object from your configuration.  Let that test run and possibly fail the build before wasting any time on integrated tests that can't succeed.

    Now, the ReSharper plugin for NHibernate sounds pretty cool.  I definitely want little or no friction in renaming or adding properties in my Domain Model classes (why I absolutely despise codegen your business object solutions).  We beat the refactoring problem by eliminating HBM.XML.  As part of my New Year's resolution to eliminate my exposure to angle bracket hell, we've created the beginning of a Fluent Interface API to express NHibernate mappings.  Using copious amounts of Generics (I guess .Net code just "wants" to have lots of angle brackets) and lambda expressions, we're able to express NHibernate mappings in a completely compiler-checked, ReSharper-able way.  Since we switched to the FI, we've experienced far less trouble with mapping problems.  Here's a couple of examples:

        // Simple class with properties and a single "to-many" relationship
        public class CustomerContactMap : ClassMap<CustomerContact>
        {
            public CustomerContactMap()
            {
                Map(x => x.Name);
                Map(x => x.Email);
                Map(x => x.Extension);
                Map(x => x.FaxNumber);
                Map(x => x.TelephoneNumber);
                Map(x => x.Title);
                References(x => x.Customer);
            }
        }
        
        // Class with a "Component"
        public class CustomerDeliveryAddressMap : ClassMap<CustomerDeliveryAddress>
        {
            public CustomerDeliveryAddressMap()
            {
                Map(x => x.Name);
                References(x => x.Customer);
                Component<Address>(x => x.Address, m =>
                   {
                       m.Map(x => x.AddressLine1);
                       m.Map(x => x.AddressLine2);
                       m.Map(x => x.AddressLine3);
                       m.Map(x => x.CityName);
                       m.Map(x => x.CountryName);
                       m.References(x => x.State);
                       m.References(x => x.PostalCode);
                   });
            }
        }
        
        // Class with some "has many" relationships
        public class CustomerMap : ClassMap<Customer>
        {
            public CustomerMap()
            {
                HasMany<CustomerContact>(x => x.Contacts).CascadeAll();
                HasMany<CustomerJob>(x => x.Jobs).CascadeAll();
                HasMany<CustomerDeliveryAddress>(x => x.DeliveryAddresses).CascadeAll();
    
                Map(x => x.Name);
                Map(x => x.LookupName);
                Map(x => x.IsGeneric);
                Map(x => x.RequiresPurchaseOrder);
                Map(x => x.Retired);
            }
        }
        
        
            

    With this approach, and backed up with the little PersistenceSpecification tests, we can happily change class names and property names with relative confidence.  Besides, the simple usage of Intellisense plus compiler safe code cuts down on the number of mapping errors.  We're more or less greenfield at the moment, so we can get away with generating the database from our NHibernate mappings on demand, but you can specify specific table and column names in the language above for brownfield scenarios.  I'd very confidently say that we're faster with this approach than we would be with HBM.XML.

    If you're interested, the complete code for everything I talked about is in the ShadeTree.DomainModel project in the StoryTeller codebase (and effectively released under the Apache 2.0 license). The code is at http://storyteller.tigris.org/svn/storyteller/trunk/. Use the src\ShadeTree.sln for this stuff. I don't know that we'll ever get around to a fully supported release of this stuff, but I wanted to throw out the idea anyway. At this point I'm only extending this code when we need something new for our current project.  A lot of the advantages of this approach are tied to application specific conventions and also by tieing the forward generation of the database structure to validation rules.

     

    As for IoC container testing...

    I'll overlook the fact that my friend David also implicitly implied that an IoC container not named StructureMap was the de facto standard. Bil Simser posted a little snippet of code to smoke test the configuration of one of those other IoC containers.  StructureMap has had quite a bit of diagnostic support since version 0.85 (StructureMapDoctor.exe), but StructureMap 2.5 will add the ability to do this:

            [SetUp]
            public void SmokeTestStructureMapConfiguration()
            {
                ObjectFactory.AssertConfigurationIsValid();
            }
            

    This will attempt to build every possible configured instance in StructureMap, perform any designated environment tests (like trying to connect to a database), and generate a complete report of all errors encountered by StructureMap.  If you're aggressive about managing all external services and configuration into your IoC container, this diagnostic test can go a long way towards detecting environmental and configuration errors of a code installation.

  • StructureMap and StoryTeller plans

    Just a quick update on stuff because I got a lot of questions about StoryTeller over the weekend.  I'm currently focusing my attention on StructureMap.  I'm giving it the Python 3000 treatment and pretty well gutting some of the internals to clean up the structure.  I've eliminated some obscure features, but you're perfectly safe if you use the documented public interfaces.  Once that's done, I've got just a little bit more functionality to add and I need to rewrite the documentation.  I gave an impromptu (and it showed) session at ALT.NET Seattle on my lessons learned for extending a framework over 4+ years.  I'll write a paper of some sort on that this spring.

    As for StoryTeller, I got quite a bit of interest in it over the weekend and I've had a couple emails lately as well.  I was close to giving up, but some of the things on the horizon that I thought would eliminate its usefulness turned out to be Java only or so far over the horizon to be effectively nonexistent.  The engine such as it is has been done for almost a year.  I'm going to rewrite the skin of the UI in WPF just to get my hands a bit dirtier with WPF.  I've done enough experimentation with some crude Intellisense for Fit tests to say that I'll be able to make Fit test editing much more efficient.  I'll update again later this spring.

  • AutoMocker in StructureMap 2.5

    Steve Harman asked me yesterday to show a little demo of the AutoMocking container coming soon in StructureMap 2.5.  Honestly, I was very lukewarm to the idea of an "AutoMocking" container at first because I thought it would obfuscate tests.  Everyone else was doing it, so I figured I'd give it a shot too and I built an automocker into StructureMap.  I'm not entirely thrilled with the API as it stands, so any feedback would be very welcome.

    My advice for the last four years has remained pretty consistent:  use StructureMap (or container of your choice) in unit tests very sparingly.  Just use plain Jane constructor injection inside your unit tests.  That advice aside, what you end up with is a lot of boring, repetitive code like this sample from StoryTeller that tests a class called WikiTextPresenter:

            private MockRepository _mocks;
            private IWikiTextEditor _editor;
            private ITestFormatConverter _converter;
            private WikiTextPresenter _presenter;
    
            [SetUp]
            public void SetUp()
            {
                _mocks = new MockRepository();
                _editor = _mocks.CreateMock<IWikiTextEditor>();
                _converter = _mocks.CreateMock<ITestFormatConverter>();
    
                _presenter = new WikiTextPresenter(_editor, _converter);
            }
    
    

    It's simple code, but it's code that you write over and over and over again to do interaction testing.  Instead, what if we wrote something that can

    1. Look at the constructor of the WikiTextPresenter class being tested above
    2. See that it requires an IWikiTextEditor and an ITestFormatConverter in its constructor
    3. Create a mock object for each of WikiTextPresenter's dependencies
    4. Poke all the mock objects into WikiTextPresenter for us
    5. And lastly, give us easy access to both the class under test and all the mock objects that the class under test depends on

    That in a nutshell is an automocking container.

    After seeing what the Eleutian guys were doing, I wanted something similar to their AutoMocking container just to eliminate the repetitious code of building mock objects and ramming them through a constructor function.  I built a new assembly in StructureMap called StructureMap.AutoMocking.  Inside it is a class called RhinoAutoMocker that extends the RhinoMocks MockRepository class with some StructureMap magic.  RhinoAutoMocker's responsibility in life is to connect the right mocks and/or stubs to the class under test, freeing you from the monotonous code shown up above.  Specifically, you use a generic parameter to tell the RhinoAutoMocker what the concrete class under test is.  The class itself is below.  After the break, I'll talk about usage.

        // Note that it subclasses the RhinoMocks.MockRepository class
        public class RhinoAutoMocker<TARGETCLASS> : MockRepository where TARGETCLASS : class
        {
            private readonly AutoMockedInstanceManager _manager;
            private TARGETCLASS _classUnderTest;
    
            public RhinoAutoMocker()
            {
                RhinoMocksServiceLocator locator = new RhinoMocksServiceLocator(this);
                _manager = new AutoMockedInstanceManager(locator);
            }
    
            // Replaces the inner InstanceManager in ObjectFactory with the mocked
            // InstanceManager from the auto mocking container.  This will make ObjectFactory
            // return mocks for everything.  Use cautiously!!!!!!!!!!!!!!!
            public void MockObjectFactory()
            {
                ObjectFactory.ReplaceManager(_manager);
            }
    
            // Gets the ClassUnderTest with mock objects (or stubs) pushed in
            // for all of its dependencies
            public TARGETCLASS ClassUnderTest
            {
                get
                {
                    if (_classUnderTest == null)
                    {
                        _classUnderTest = _manager.FillDependencies<TARGETCLASS>();
                    }
    
                    return _classUnderTest;
                }
            }
    
            // I find it useful from time to time to use partial mocks for the ClassUnderTest
            // Especially in Presenter testing
            public void PartialMockTheClassUnderTest()
            {
                _classUnderTest = PartialMock<TARGETCLASS>(getConstructorArgs());
            }
    
            private object[] getConstructorArgs()
            {
                ConstructorInfo ctor = Plugin.GetGreediestConstructor(typeof (TARGETCLASS));
                List<object> list = new List<object>();
                foreach (ParameterInfo parameterInfo in ctor.GetParameters())
                {
                    Type dependencyType = parameterInfo.ParameterType;
                    object dependency = _manager.CreateInstance(dependencyType);
                    list.Add(dependency);
                }
    
                return list.ToArray();
            }
    
            // Get one of the mock objects that are injected into the constructor function
            // of the ClassUnderTest
            public T Get<T>()
            {
                return _manager.CreateInstance<T>();
            }
    
            // Set the auto mocking container to use a Stub for Type T
            public void InjectStub<T>(T stub)
            {
                _manager.InjectStub<T>(stub);
            }
        }
    

    In usage it looks like this for the WikiTextPresenter class we looked at up top.  The test specifies that when ApplyChanges() is called on WikiTextPresenter, it will take the raw text from its view (IWikiTextEditor), convert that text to the internal data structure with ITestFormatConverter, and finally update some information in the View.

            [Test]
            public void ApplyChanges_with_the_automocker()
            {
                RhinoAutoMocker<WikiTextPresenter> mocks = new RhinoAutoMocker<WikiTextPresenter>();
                using (mocks.Record())
                {
                    Test test = new Test();
                    mocks.ClassUnderTest.TestPart = test;
    
                    string theWikiText = "!|SomeFixture|";
                    Expect.Call(mocks.Get<IWikiTextEditor>().WikiText).Return(theWikiText);
    
                    WikiVersion expectedVersion = new WikiVersion(0, theWikiText);
                    mocks.Get<ITestFormatConverter>().ApplyChangesFromWiki(test, theWikiText);
                    mocks.Get<IWikiTextEditor>().AddWikiVersionToList(expectedVersion);
                    mocks.Get<IWikiTextEditor>().SetWikiVersion(expectedVersion);
                }
    
                using (mocks.Playback())
                {
                    mocks.ClassUnderTest.ApplyChanges();
                }
            }
    

    RhinoAutoMocker creates the WikiTextPresenter instance under test on the first call to RhinoAutoMocker.ClassUnderTest.  The Get<T>() method on RhinoAutoMocker simply retrieves the mock object of type T that was used to construct the class under test.  Otherwise, all other usage is just the normal RhinoMocks usage.

    In case you're wondering, I chose RhinoMocks because:

    1. RhinoMocks is probably the most common mocking tool by a large margin.  It's what I use, and I ultimately wanted a tool for me;)
    2. NMock/NMock2 seems to be dead.  I finally eliminated the direct NMock support from StructureMap for the 2.5 release anyway.
    3. If you're using TypeMock you probably don't care about dependency injection and automocking anyway

    Making the RhinoAutoMocker subclass MockRepository just seemed like a good way to have all of the RhinoMocks capabilities right there at hand instead of wrapped up behind the scenes.

     

     

    If you want to use this now, you need to download the very latest code out of StructureMap's subversion repository at https://structuremap.svn.sourceforge.net/svnroot/structuremap/trunk.  Like I've said before, I'm basically done with coding on 2.5, but I'm not releasing officially until I can do a full rewrite of the website and documentation.

     

  • Interception techniques in StructureMap 2.5

    The 2.5 release of StructureMap is at least 6 weeks away, but I'd like to throw some more stuff out to get some feedback while I've got plenty of time to deviate.  I'm building in much more interception capabilities into StructureMap to support runtime AOP and other scenarios.  I don't have a good background in AOP, so I'm guessing as much as anything about what I need.  Here's a rundown of what I've got so far.  The code is targeted to .Net 2.0.  My plan is to release for 2.0, then immediately turn around and do a .Net 3.5 release.  So please mentally substitute in lambda expressions for the anonymous delegates.  All of this code is in the StructureMap trunk, and I'm running my development project off of the current revision.

     

    Intercept a particular instance being created

    When a particular instance is created you want to do something with that instance before it's returned from StructureMap.  The configuration code is below:

     

                registry.ForRequestedType<IService>()
                    .AddInstance(
                    Instance<IService>().UsingConcreteType<ColorService>()
                        .OnCreation<ColorService>(delegate(ColorService s) { _lastService = s; })
                    );

    You just pass a delegate or lambda expression to the OnCreation() method like this:

        public delegate void StartupHandler<T>(T target);

    I envision this being used mostly to run extra bootstrapping or register objects with event brokers.  Now, if you want to enrich the object with some sort of runtime AOP or wrap it with a decorator, you would do this:

     

                registry.ForRequestedType<IService>()
                    .AddInstance(
                    Instance<IService>().UsingConcreteType<ColorService>()
                        .EnrichWith<IService>(delegate(IService s) { return new DecoratorService(s); })
                    )

     

    Again, you just pass in a delegate or lambda into the EnrichWith() method, but this time you're required to return an object.  The delegate signature is this:

        public delegate T EnrichmentHandler<T>(T target);

    It might be tedious to define these handlers per instance, so let's move on to broader categories.

     

    Intercept every instance of a requested type

    It's basically the same mechanics, except that you register the EnrichmentHandler or StartupHandler on the ForRequestedType<T> (BuildInstancesOf<T>) expression like these examples:

                _registry.ForRequestedType<IService>()
                    .OnCreation(delegate(IService s) { _lastService = s; })
                    .AddInstance(
                    ConstructedBy<IService>(delegate { return new ColorService("Green"); })
                        .WithName("Green"))
                    ;
     
     
                _registry.ForRequestedType<IService>()
                    .EnrichWith(delegate(IService s) { return new DecoratorService(s); })
                    .AddInstance(
                    ConstructedBy<IService>(delegate { return new ColorService("Green"); })
                        .WithName("Green"))
                    ;

     

    The first snippet directs StructureMap to execute a delegate against every new instance of IService created.  The second snippet would give you the ability to replace any new instance of type IService created with an enriched type or decorator.

    All of these examples so far have worked on an object created by StructureMap shortly after it was created.  Now, what if you want to intercept the request itself and return something entirely different depending on circumstances?  For a couple years, StructureMap has an extensibility mechanism called an InstanceFactoryInterceptor that acts much as an IHttpModule in ASP.Net to decorate the normal InstanceFactory object that builds a given family of instances.  I've used that mechanism to create the "scoping" feature that allows you to make instances either singleton's or thread local or HttpContext specific.  As I said, it's been a feature for awhile, but never documented and got cut from the original release of the fluent interface.  I'm fixing that with the 2.5 release like so:

                AnInstanceFactoryInterceptor factoryInterceptor = new AnInstanceFactoryInterceptor();
     
                PluginGraph pluginGraph = new PluginGraph();
                using (Registry registry = new Registry(pluginGraph))
                {
                    registry.BuildInstancesOf<IGateway>().InterceptConstructionWith(factoryInterceptor);
                }
     

    I suppose you could use this to register an AOP handler, but I see this primarily as a way to do instance caching or switch out the actual instances returned by some sort of security rules.  You might use this to return a read only implementation of IView for some roles, and an editable implementation of IView for other roles.

    Intercept any instance of any type that meets this criteria

    Okay, now we come to the feature that's very specifically intended for AOP.  What if you want your runtime AOP engine to intercept any type that's decorated with the magic AOP attributes?  You could implement a new class that implements the TypeInterceptor interface shown below:

        public interface InstanceInterceptor
        {
            object Process(object target);
        }
     
        public interface TypeInterceptor : InstanceInterceptor
        {
            bool MatchesType(Type type);
        }

    You just need to implement two methods.  MatchesType(Type) can look at a .Net Type and determine if the TypeInterceptor can act upon an instance.  The Process() method acts as the EnrichmentHandler delegate to return any kind of decorator or runtime AOP proxy instead of the original instance.  You would register TypeInterceptor like this:

     

                MockTypeInterceptor interceptor = new MockTypeInterceptor();
                registry.RegisterInterceptor(interceptor);
     
                // or
     
                StructureMapConfiguration.RegisterInterceptor(interceptor);

    You can register more than one TypeInterceptor.  The result of MatchesType() is cached by Type, so subsequent creations of a concrete class will not have to call expensive reflective calls to match the types.

     

     

    Well, waddaya think?  Useful, or do you need something else entirely?

  • Some new ways to build objects in StructureMap with less configuration

    I'm getting close to code complete on the forthcoming 2.5 release of StructureMap and I'm focusing on ease of use features and fullblown interception support for AOP tooling (runtime AOP to be provided by something else though).  StructureMap has had some support in the last couple releases to "fill" a concrete class with dependencies by calling ConcreteClass concreteClass = ObjectFactory.FillDependencies<ConcreteClass>().  The advantage being that you didn't have to explicitly register ConcreteClass with the configuration. 

    After

    1. Having somebody ask me how to do it
    2. Seeing a demo of another container do this (I'm not sure about my "NDA" on this, so I'm not gonna say which)
    3. Basically wanting a better way to do this for my current project

    I decided to just add it. 

    As of today (in the trunk at least) you can simply request a concrete class through the normal ObjectFactory.GetInstance<T>() method, and if StructureMap can resolve the dependencies, ObjectFactory will happily return the class requested.  Taking it a step farther, say you have a class with this constructor:  public TradePresenter(Trade trade, ITradeView view, ITradeRepository repository).  You can also do this now:  TradePresenter presenter = ObjectFactory.With<Trade>(someTradeVariable).GetInstance<TradePresenter>() and you can get a TradePresenter object built with all of its dependencies (an ITradeView & ITradeRepository) plus pass the exact instance of the Trade class into the TradePresenter's constructor function.

    All of this is in the Subversion trunk.  If you feel like downloading it out of SVN and playing with it, I'd appreciate the feedback.  Below is the unit test I'm using to prove out the implicit configuration:

            [Test]
            public void CanBuildConcreteTypesThatAreNotPreviouslyRegistered()
            {
                // Create a new InstanceManager that has a default instance configured for only the
                // IProvider interface.  InstanceManager is the real "container" behind ObjectFactory
                Registry registry = new Registry();
                registry.ForRequestedType<IProvider>().TheDefaultIsConcreteType<Provider>();
                InstanceManager manager = (InstanceManager) registry.BuildInstanceManager();
     
                // Now, have that same InstanceManager create a ClassThatUsesProvider.  StructureMap will
                // see that ClassThatUsesProvider is concrete, determine its constructor args, and build one 
                // for you with the default IProvider.  No other configuration necessary.
                ClassThatUsesProvider classThatUsesProvider = manager.CreateInstance<ClassThatUsesProvider>();
                Assert.IsInstanceOfType(typeof(Provider), classThatUsesProvider.Provider);
            }
     

    Here's another example of using the new explicit arguments functionality.  The relevant code is bolded:

            [Test]
            public void NowDoItWithObjectFactoryItself()
            {
                StructureMapConfiguration.ForRequestedType<ExplicitTarget>().TheDefaultIs(
                    Registry.Instance<ExplicitTarget>()
                        .UsingConcreteType<ExplicitTarget>()
                        .Child<IProvider>().IsConcreteType<RedProvider>()
                        .WithProperty("name").EqualTo("Jeremy")
                    );
     
                ObjectFactory.Reset();
     
                // Get the ExplicitTarget without setting an explicit arg for IProvider
                ExplicitTarget firstTarget = ObjectFactory.GetInstance<ExplicitTarget>();
                Assert.IsInstanceOfType(typeof (RedProvider), firstTarget.Provider);
     
                // Now, set the explicit arg for IProvider
                BlueProvider theBlueProvider = new BlueProvider();
                ExplicitTarget secondTarget = ObjectFactory.With<IProvider>(theBlueProvider).GetInstance<ExplicitTarget>();
                Assert.AreSame(theBlueProvider, secondTarget.Provider);
            }

    Feedback on the syntax and/or usefulness of these features would be very appreciated.

  • Spiking a new syntax for integration tests. Whaddaya think?

    Hello, my name is Jeremy, and I sometimes write unit tests specifications that are uglier than sin.  Specifically, when I started to look back at the interaction style tests I've been writing over the past couple years I'm finding a bunch of unit tests that are indecipherable to me, the author of those very tests.  I came to the conclusion that I needed to start writing my interaction tests in a different fashion to promote readability -- and hence better maintainability. 

    I was really concerned about readability more than anything else, but a quicker way to write integration tests would be nice to.  To that end, I've been following the Eleutian guys' posts on their AutoMockingContainer strategy.  Honestly, I've been dubious about the value of the AutoMockingContainer idea.  I get the mechanical savings, but worried that it was too much magic that would obfuscate the unit tests somewhat.  I've got the StructureMap code open for its upcoming 2.5 release, so I decided to stick in some facility for "AutoMocking." 

    The auto mocking stuff was easy enough to do, but I wanted to go farther in terms of readability.  I've found that one of the factors related to integration tests being confusing to newbies and hard to read for anyone is simply the order in which things happen.  In the traditional RhinoMocks record/replay model I call a bunch of expectations on the mock objects, then perform the actual action on the class under test, then call VerifyAll().  It's Yoda syntax.  Instead, what if we could express the tests in a more natural order of Given blah, when I execute blah, this stuff should happen.

    Here's what I came up with in my spike.  This is working code, but I don't want to talk about the mechanics of the underlying code.  I'm mostly interested in what y'all think about the syntax and flow of the test.  I'm purposely leaving out comments or trying to explain the grammar upfront because I want to see how "soluble" this syntax is if you're looking at it cold.

    This is a rewrite of an existing unit test in StoryTeller.  Upon looking at the code, I think there was a simpler way to write the code, but that's a refactoring for another day.  The new and old code effectively express the exact same unit test.  The auto mocking does do a lot to cut down on monotonous setup code.  I definitely think this code is going to be smoother in C# 3.0, but I want to release a 2.0 version before I do that.

    The New Code

            [Test]
            public void Execute_the_command()
            {
                string theFragmentName = "Fragment1";
                Fragment theNewFragment = new Fragment(theFragmentName);
                
                GivenThatThe<Suite>().Is(new Suite());
    
                Given = delegate {
                    That.Calling(Service<IInputCommand>().PropertyValue).Return(theFragmentName);              
                };
    
                WhenExecuting = delegate  {
                    AddNamedFragmentCommand.Execute();
                };
    
                TheInteractionShouldBe = delegate {
                    Call<ISystemUnderTest>().Save(theNewFragment);
                    Call<ILeafNode>().RefreshNodes();
                    Call<IFragmentPresenter>().StartEditing(theNewFragment, Member<ISystemUnderTest>());
                    Call<IApplicationController>().OpenScreen(Member<IFragmentPresenter>());
                };
    
                Then = delegate {
                    Assert.IsNotNull(Member<Suite>().FindFragment(theFragmentName));           
                };
            }
    
    

    The Old Code for the Same Test

            [SetUp]
            public void SetUp()
            {
                _mocks = new MockRepository();
                _node = _mocks.CreateMock<ILeafNode>();
                _suite = new Suite();
                _systemUnderTest = _mocks.CreateMock<ISystemUnderTest>();
                _inputDialog = _mocks.CreateMock<IInputCommand>();
    
                _applicationController = _mocks.CreateMock<IApplicationController>();
    
                _command =
                    new AddNamedFragmentCommand(_node, _suite, _systemUnderTest, _inputDialog, _applicationController);
            }
    
            #endregion
    
            private MockRepository _mocks;
            private ILeafNode _node;
            private Suite _suite;
            private ISystemUnderTest _systemUnderTest;
            private IInputCommand _inputDialog;
            private AddNamedFragmentCommand _command;
            private IApplicationController _applicationController;
    
            [Test]
            public void Execute()
            {
                string theFragmentName = "Fragment1";
                And fragmentConstraint = new And(
                    new TypeOf(typeof (Fragment)),
                    new PropertyIs("Name", theFragmentName)
                    );
    
                IFragmentPresenter fragmentPresenter = _mocks.CreateMock<IFragmentPresenter>();
                ObjectFactory.InjectStub(typeof (IFragmentPresenter), fragmentPresenter);
    
    
                Expect.Call(_inputDialog.PropertyValue).Return(theFragmentName);
    
    
                // Save the fragment
                _systemUnderTest.Save(null);
                LastCall.Constraints(fragmentConstraint);
    
                _node.RefreshNodes();
    
                // Open the screen
                fragmentPresenter.StartEditing(null, _systemUnderTest);
                LastCall.Constraints(fragmentConstraint, new Equal(_systemUnderTest));
                _applicationController.OpenScreen(fragmentPresenter);
    
                _mocks.ReplayAll();
                _command.Execute();
                _mocks.VerifyAll();
    
                Assert.IsNotNull(_suite.FindFragment(theFragmentName));
            }
    

     

  • Using StructureMap to build a class that isn't registered with the container

    I had a query this morning about this.  Say you're working in the new MVC framework and you write your own routing engine that has a syntax like this:

      Route("some string pattern").IsHandledBy<MyController>();
    Route("some other string pattern").IsHandledBy<AnotherController>();

    Each Controller has its own set of dependencies that you'd prefer that StructureMap build out for you, but it might be inconvenient to have to register all these types with StructureMap.  That's okay.  As long as you know the concrete type you want, StructureMap can create the concrete class and "fill" it with all of the dependencies even if StructureMap isn't configured with that concrete type in advance.  The syntax is:

    MyController controller = ObjectFactory.FillDependencies<MyController>();

    or

    MyController controller = (MyController)ObjectFactory.FillDependencies(typeof(MyController));

    I don't use this feature much, but it's handy in some spots

  • Spring loading your IoC Container

    Ayende has a post up this morning called Inverting Inversion of Control where he talks about registering services with an IoC container at runtime.  Ayende is specifically saying that this technique is useful for injecting services that you either can't control the creation of or simply want to construct in another way.  It's funny that he should post this today because I've been using this technique quite a bit the last couple months in my WinForms development.  I'm breaking open the StructureMap code to start a new release today largely to add a bit more support for this scenario.  To add to the discussion, I'll throw out an example of what I'm doing.

     

    Registering pieces of the ApplicationShell

    In StoryTeller and a couple of my applications at work the ApplicationShell (main form) has grown large and complicated.  It's become advantageous to treat various parts of the main form as separate services of the user interface and let all of them be driven by separate Presenters.  For the sake of consistency with the rest of the application and avoiding nasty Law of Demeter violations, I inject these little pieces of the main form into StructureMap so that StructureMap can instantiate other services that depend on these pieces through constructor arguments.  I could create all of these little user controls and TreeNode's via StructureMap and then call methods to attach them into the ApplicationShell later, but that quickly led to bootstrapping spaghetti code left and right.  It turned out to be much cleaner to use the design time support to place the children controls onto the ApplicationShell form, inject these children into StructureMap, and let StructureMap completely setup the Presenters that depend on these child controls through their constructors.

    When I start up StoryTeller the first thing that I do is bootstrap StructureMap's configuration.  The second thing I do is create the main ApplicationShell form.  After the child In the constructor function of ApplicationShell I call the method below to register some of the child controls of ApplicationShell into StructureMap:

            private void loadShellPartsIntoStructureMap()
            {
                ObjectFactory.InjectStub(typeof (IApplicationShell), this);
                ObjectFactory.InjectStub(typeof (IContentPanel), contentPanel);
                ObjectFactory.InjectStub(typeof (IHierarchyNode), hierarchyExplorer.HierarchyNode);
                ObjectFactory.InjectStub(typeof (IFixtureExplorerView), fixtureExplorer);
            }

    The "InjectStub()" method was originally put into StructureMap to allow you to override normal StructureMap behavior to push in stubs instead of the normal service during testing.  It does also function correctly in this scenario (in the forthcoming 2.1 version I'm going to add a new method called Inject<T>(T service) ).   Regardless of any other prior configuration, StructureMap will always return the instance passed into InjectStub(Type, object) whenever an instance of the specified Type is requested.  When any other class requests IContentPanel directly or through a constructor function, the "contentPanel" child of ApplicationShell will always be returned.

    Now, moving on to see how this works.  I generally use an ApplicationController class to govern the activation and deactivation of screens in the user interface.  The ApplicationController in StoryTeller has a dependency on both the IContentPanel (the tabbing container for screens) and the IHiearchyNode (the top most TreeNode in the navigation tree).  Since we've already injected the two little children into StructureMap, we can completely set up ApplicationController through its constructor.

            public ApplicationController(
                ICommandExecutor executor, 
                IContentPanel panel, 
                IProjectRepository repository,
                ITestEventPublisher publisher, 
                IHierarchyNode hierarchyNode)
            {
                _executor = executor;
                _panel = panel;
                _repository = repository;
                _publisher = publisher;
                _hierarchyNode = hierarchyNode;
            }
     

    As long as I create ApplicationController after the StructureMap bootstrapping and the creation of ApplicationShell, I'm ready to go.  Before I switched to the path of injecting the child controls into StructureMap I had a lot more one off bootstrapping code to push around the IContentPanel and IHiearchyNode controls.  By refactoring to the "injected children" mode I cut back on a lot of undesirable coupling and trimmed down some chatty interfaces. 

    One of my little maxims of programming is to strive to put everything a class needs into a constructor so that we know the class is ready to go as soon as it's created.  This little trick of spring loading the UI controls into the IoC container gets us closer to that ideal.

  • Dependency Injection Tools still have some good years left...

     

    ...as long as we're writing code in a static typed language anyway.  Dependency Injection the pattern isn't going away, but it's full time to reconsider Dependency Injection / Inversion of Control tools.

    A couple weeks ago there was quite a bit of backlash against the usage of Dependency Injection (DI) and Inversion of Control (IoC) tools.  The pantheon of No Fluff, Just Stuff programming heroes made a game out of mocking Dependency Injection here and here.  My CodeBetter mate, Scott Bellware, even had some negative things to say on Dependency Injection tools (which I think is partially caused by him cutting his teeth on Spring.Net  ;) ).  I didn't respond because I was deep into StoryTeller and didn't quite know what my response would be anyway.  I'll admit that the practice of pulling interfaces out and opening up constructors just to slip in mock objects is beginning to feel clunky in this era of TypeMock and duck-typed languages.  One of the things I concentrated on with StructureMap 2.0 was making the configuration easier to use by programmatic alternatives, less Xml overhead, and making StructureMap less intrusive, but StructureMap is still there in your code.  I don't find it hard to use or distracting in the slightest, but maybe I need to start seeing it that way.

    Give me Ruby or Python and I probably won't feel as much need for a StructureMap.  That being said, I still think there are plenty of good reasons to use dependency injection besides the stereotypical unit testing scenarios (you've never needed an IoC tool just to attach test doubles anyway).  I've used my own StructureMap DI tool continuously for almost 4 years now and I've probably pushed the technique about as far as anybody (except for Aspect Oriented Programming (AOP) where I happily lag the curve).  Here's a list of usages for DI as a pattern with and without an IoC tool that I've found beneficial:

    1. Flexible deployment options.  For example, last year I worked on a system that ran components on 3 different servers with a couple different remoting connections.  When we first got the system you couldn't run the full stack without deploying the code to a windows service and an ASP.Net application.  Feedback was slow.  We hid the service points behind abstracted interfaces and started pulling the dependencies with StructureMap.  Once we made it to that point we simply made a different StructureMap profile that ran both the web client and server code in a single AppDomain.  The feedback cycle got quicker.  Debugging was easier.  We were able to write functional tests against the business rules engine because we could easily activate the code in process at will.  In case you're wondering, we did have some automated tests fully end-to-end as well to make sure that the real communication and deployment configuration worked. 
    2. Stubbing out inconvenient services during development.  My last project was a .Net client in front of a balky Java web service.  The web service development often lagged the .Net code and was frankly a pain in the neck to install even when it was ready.  We used a "Stubbed" Profile in our StructureMap configuration to switch between a fully connected mode and a mode that talked to an in memory repository.  While you can make the switch by command line arguments, we redirected the application with a pair of batch files called "ConnectMe" and "StubMe" just to switch the default profile in StructureMap.  No hard wired stubbing or conditional compilation necessary.
    3. I think using DI leads to more self-documenting code.  I like being able to understand the dependencies of a class just by looking at the arguments to its constructor function.  I think it makes the code be more transparent by pointing to the class's dependencies and configuration.  As pointed out originally by Jacob Profitt, this can be construed as a massive violation of encapsulation that can make a class harder to use.  That doesn't concern me particularly because I use StructureMap to chain all the dependencies together in this case so that the client of an interface doesn't need to know anything about the constructor functions of its dependencies.  Very few concrete classes should end up being directly exposed to the IoC tool.  Oddly enough, I'm generally not too concerned about the binding to StructureMap since I can pop into the code at any time to add features or fix problems.
    4. "Push" configuration is better in many ways than "Pull" configuration.  I use an IoC tool for all custom configuration needs.  Configured properties are just "pushed" into the classes that need them by the IoC tool.  The configuration now "knows" about the code but not the other way around.  My service classes are now completely usable in whole new settings because they aren't coupled to a configuration file.  More on configuration management with an IoC tool at the StructureMap homepage.
    5. Reuse.  I've found that focusing on composing a system into cohesive classes with loose coupling to each class's dependencies will allow for much simpler reuse.  If you can replace the dependencies for a class at will you can take that class and use it in an entirely new context when the need arises.  I've been able to take big chunks of a rules engine that ran in a transaction processing pipeline and use that same rules engine inside a web service.  We didn't have to change a thing in the rules engine, just push in different implementations of it's dependencies.  Having the engine decoupled from its configuration also made it more reusable when we needed to pull the configuration from an alternative source in the new web service.
    6. Easy to change the behavior of the system by swapping out implementation of some of the services or adding new components to the system.  One of the common things to do with an IoC tool is to define Chain of Responsibility handlers in the IoC tool so that it's easy to plug in new handlers or reorder the existing handlers to add or change behavior.
    7. Built in Environment Tests.  I don't know if any of the other IoC tools besides StructureMap has them, but I've used them to great effect in the past.  It's especially valuable for distributed systems development and for highly iterative development that requires very frequent testing deployments.
    8. If you want pluggability for your own services, the Provider model sucks compared to any of the IoC tools.  Seriously, the implementation of the Provider model is limited in capability compared to any IoC tool.  If you want pluggability, I think you'll find that any of the common IoC tools are more useful than building your own Provider type.  Specifically, with an IoC tool you don't need to inherit from a particular base class, you have more freedom to compose dependencies rather than build one gigantic, overweight class, and you have more options for configuration storage and runtime pluggability than the Provider model supports.

     

    Regardless...

    So, is Dependency Injection still good, or just baggage from yesterday that needs to be cleared away so we can continue to progress?  It seems perverse to me to be wrestling with this question since Dependency Injection is still relatively new and hasn't even come close to crossing the chasm inside the .Net community.  Heck, Microsoft is just starting to support DI strategies in some of the Patterns and Practices work and Acropolis (but clumsily)!  It's a harder question for me since I've invested quite a bit of time over the last 4 years building and using a DI/IoC tool.

    I think it's fair and accurate to say that some of the goals of using Dependency Injection in a static typed language can be realized through simpler mechanisms in dynamic typed languages.  I still think you want to use Dependency Injection in Ruby because the rules of OOP still apply, but maybe the fancy IoC tools largely go away.  I could use much more experimentation, but Ruby style metaprogramming does seem much simpler in mechanics and readability to me than using DI engines and AOP in C# to enrich behavior.  Despite how many words I just used above to extol the benefits of IoC/DI that I've already enjoyed, it is time to reconsider this technique's place in my toolbox as we move forward.

  • Build your own CAB #14: Managing Menu State with MicroController's, Command's, a Layer SuperType, some StructureMap Pixie Dust, and a Dollop of Fluent Interface

    THIS ARTICLE IN ITS ENTIRETY IS HERE.

    The title is a mouthful and accurately implies an alarmingly high jargon to code ration, but I just didn't see anyway to write this post without straying into all of these different subjects.  When you try to write an explanatory article you have to walk a tightrope between a sample problem that's simple enough to work through in no more than a handful of pages and a sample problem that's just too simplistic to be valuable.  I'll leave it up to you to decide which end of the spectrum this one falls on.  I also had a rough time trying to decide on the best way to order the topics in the narrative.  All I can do is ask you to scan the following headers if something seems to be missing or I'm lurching ahead.

    Last week I had a flood of people follow Martin Fowler's link into this series.  I thought it was pretty c