Fork me on GitHub

Configuring Lifecycles Edit on GitHub

Unless designated otherwise, StructureMap uses Transient as the default scope for all configured Instance's.

The resolution of the lifecycle for any given Instance is to check:

  1. Use the explicitly configured lifecycle for the Instance
  2. If no lifecycle is configured for the Instance, use the explicitly configured lifecycle for the Plugin Type
  3. If no lifecycle is configured for either the Instance or the Plugin Type, use the default Transient lifecycle

The lifecycle precedence rules and the syntax for configuring object lifecycles are shown below:

public void lifecycle_precedence()
    var container = new Container(x =>

        // Configure the default lifecycle for
        // a PluginType (Rule)

        // Configure the lifecycle for a single Instance

    // The default lifecycle is Transient

    // Override at the Family

    // 'C' is the default lifecycle for Rule (SingletonThing)

    // 'A' is a transient

    using (var nested = container.GetNestedContainer())
        // 'B' is always unique

Using Attributes

New in StructureMap 4.0 are some simple attributes to mark either a complete Plugin Type or a single Instance as either a singleton or using the always unique lifecycle:

The usage is shown below:

public interface IShouldBeUnique { }

[Singleton] // because the most wonderful thing about Tiggers is that I'm the only one....
public class Tigger { }

See Using Attributes for Configuration for information about adding your own custom attibutes for other lifecycles.