Mar 10 2010

StructureMap Quick Start

Category: Software DevelopmentJeff @ 05:43

A friend asked me for help getting started with StructureMap. I thought it might help someone else, so here it is in all of its simplicity.  Please let me know if this helps you or if you have anything to add.

--------------------------------
using StructureMap;
using StructureMap.Configuration.DSL;

public class Bootstrapper
{
    public void Bootstrap()
    {
        ObjectFactory.Initialize(init =>
        {
            init.Scan(scan =>
                {
                    scan.AssembliesFromApplicationBaseDirectory();
                    scan.WithDefaultConventions();
                }
        }
    }
}

You can pass a predicate to "AssembliesFromApplicationBaseDirectory" to restrict it to only scan assemblies that match a rule you specify ( in case you want to only scan your assemblies, and not any referenced assemblies you may be working with - very handy).

You can also do things like "scan.AssemblyContainingType<MYTYPE>();" where MYTYPE is a type in an assembly in which you want to scan for services/dependencies.

The call to "WithDefaultConventions()" tells StructureMap to wire up interfaces like "IFooService" with concrete implementations like "FooService".

If you need to change things you can add initialization expressions in the init section:

init.For<IMyService>().Use<MyReplacementService>();

There's a lot more to it, but this is a good start.

Tags: , ,

Comments are closed