New in version 1.0 is the ability to quickly define different creation modes.  This functionality can be configured with the new optional "Scope" property on the [PluginFamily] attribute or the "Scope" attribute on the <PluginFamily> node.  The alternatives are:

  1. PerRequest - The default operation.  A new instance will be created for each request.
  2. Singleton - A single instance will be shared across all requests
  3. ThreadLocal - A single instance will be created for each requesting thread.  Caches the instances with ThreadLocalStorage.
  4. HttpContext - A single instance will be created for each HttpContext.  Caches the instances in the HttpContext.Items collection.
  5. HttpSession - A single instance will be created for each HttpSession.  Caches the instances in the HttpContext.Session collection.  Use with caution.
  6. Hybrid - Uses HttpContext storage if it exists, otherwise uses ThreadLocal storage.

Setting the Scope in the Registry DSL

The Scope is set in the Registry DSL with the CacheBy() method off of a call to ForRequestedType<T>():

            var container = new Container(x =>

            {

                x.ForRequestedType<IGateway>().CacheBy(InstanceScope.Singleton).TheDefaultIsConcreteType

                    <SingletonShouldBeLazy>();

            });


Setting the Scope in the Xml Configuration

In Xml configuration, you have two choices for specifying (there's a third legacy way, but it's not pretty) the scope.  If you use the older <PluginFamily> node, the Scope attribute designates the lifecycle.  The valid values are the string representations of the InstanceScope enumeration shown in the bullet list above.

<StructureMap>

  <PluginFamily

    Type="StructureMap.Testing.Widget.Column"

    Assembly="StructureMap.Testing.Widget"

    DefaultKey=""

    Scope="ThreadLocal">

  </PluginFamily>

 

</StructureMap>

StructureMap 2.0 introduced a more concise Xml format with the <DefaultInstance> node.  Once again, the lifecycle is set by the Scope attribute on the <DefaultInstance> node:

<StructureMap MementoStyle="Attribute">

  <DefaultInstance

    PluginType="StructureMap.Testing.Widget.Rule,StructureMap.Testing.Widget"

    PluggedType="StructureMap.Testing.Widget.ColorRule,StructureMap.Testing.Widget"

    Color="Blue"

    Scope="Singleton"

    Name="TheBlueOne"/> 

</StructureMap>

In all cases, the lifecycle is "PerRequest" if not explicitly specified.  If you are coming from other .Net IoC containers, this is a different behavior (and one that *I* feel was correct to begin with).


Setting the Scope with the PluginFamily Attribute

Using attributes is somewhat deprecated, but still possible.  See Using Attributes for more information on setting the Scope from an attribute.


Using a Custom Scope/Lifecycle

Lastly, you can build a custom scope/lifecycle and plug it into StructureMap.  See Extending StructureMap for more information.