<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:copyright="http://blogs.law.harvard.edu/tech/rss" xmlns:image="http://purl.org/rss/1.0/modules/image/">
    <channel>
        <title>AbstractCode</title>
        <link>http://abstractcode.com/abstractblog/Default.aspx</link>
        <description>Code too abstract to instantiate</description>
        <language>en-AU</language>
        <copyright>Colin David Scott</copyright>
        <generator>Subtext Version 2.5.1.20</generator>
        <image>
            <title>AbstractCode</title>
            <url>http://abstractcode.com/abstractblog/images/RSS2Image.gif</url>
            <link>http://abstractcode.com/abstractblog/Default.aspx</link>
            <width>77</width>
            <height>60</height>
        </image>
        <item>
            <title>Avernus Framework: Part 2 - Domain Events</title>
            <category>Avernus</category>
            <category>Development Tools</category>
            <link>http://abstractcode.com/abstractblog/archive/2011/02/08/avernus-framework-part-2-domain-events.aspx</link>
            <description>&lt;blockquote&gt;   &lt;p&gt;Index&lt;/p&gt;    &lt;p&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2011/02/06/avernus-framework-part-0-introduction.aspx"&gt;Part 0 – Introduction&lt;/a&gt;       &lt;br /&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2011/02/06/avernus-framework-part-1-persistence.aspx"&gt;Part 1 – Persistence&lt;/a&gt;       &lt;br /&gt;Part 2 - Domain Events &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;There are many advantages to building a full domain model. However it is not immediately obvious how business logic inside classes mapped using an ORM can invoke behaviours outside the domain. Invoking services directly involves tight coupling and is difficult to test. Doing dependency injection into domain classes is problematic as they are controlled by another container (the ORM).&lt;/p&gt;  &lt;p&gt;As with so many things Udi Dahan has an excellent summary of the issue and an effective solution for it. See &lt;a href="http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models/"&gt;How to create fully encapsulated Domain Models&lt;/a&gt;, &lt;a href="http://www.udidahan.com/2008/08/25/domain-events-take-2/"&gt;Domain Events – Take 2&lt;/a&gt;, &lt;a href="http://www.udidahan.com/2009/06/14/domain-events-salvation/"&gt;Domain Events – Salvation&lt;/a&gt;. I consider his final solution excellent and have simply integrated it into Avernus.&lt;/p&gt;  &lt;p&gt;The domain event support revolves around three primary types:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;em&gt;IDomainEvent&lt;/em&gt; is a marker interface that is applied to data classes to indicate they are a raiseable event.&lt;/li&gt;    &lt;li&gt;&lt;em&gt;IHandleDomainEvents&amp;lt;T&amp;gt;&lt;/em&gt; is the interface that defines the contract to be implemented by anything wishing to handle domain events. Multiple types may implement this interface, the order in which they are invoked is not defined.&lt;/li&gt;    &lt;li&gt;&lt;em&gt;DomainEvents&lt;/em&gt; is a static class that handles raising events.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;We start by configuring DomainEvents to use the appropriate StructureMap container:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;DomainEvents.Container = ObjectFactory.Container;&lt;/pre&gt;

&lt;p&gt;This specifies the default container, but a custom container may also be used.&lt;/p&gt;

&lt;p&gt;A domain event is simply a data transfer object that implements &lt;em&gt;IDomainEvent&lt;/em&gt;. A typical example is contained in the Avernus Store sample code:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;public class OrderAddedEvent : IDomainEvent
{
    public Order Order { get; set; }
}&lt;/pre&gt;

&lt;p&gt;Note that this is named in the past tense. Domain events signal things that have happened in the domain rather than indicating that things are happening or will happen. This rule should only be violated under exceptional circumstances. As domain events are transient it is acceptable to have publically settable properties. Event handlers should not modify these properties. If they have a need to modify the domain then they can make (constrained) calls using the instances in the event object.&lt;/p&gt;

&lt;p&gt;A typical domain event handler looks like:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;public class OrderAddedHandler : IHandleDomainEvents&amp;lt;OrderAddedEvent&amp;gt;
{
    public void Handle(OrderAddedEvent instance)
    {
        Console.WriteLine(instance.Order.ReferenceNumber);
    }
}&lt;/pre&gt;

&lt;p&gt;Handlers are retrieved from the StructureMap container and must therefore be registered with the container. This can be accomplished by adding a call to &lt;em&gt;ConnectImplementationsToTypesClosing&lt;/em&gt; in the StructureMap configuration:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;initialise.Scan(scan =&amp;gt;
    {
        scan.TheCallingAssembly();
        scan.ConnectImplementationsToTypesClosing(typeof(IFetchingStrategy&amp;lt;&amp;gt;));
        scan.ConnectImplementationsToTypesClosing(typeof(IHandleDomainEvents&amp;lt;&amp;gt;));
    });&lt;/pre&gt;

&lt;p&gt;Once the handler has been registered we can raise a domain event. Consider the &lt;em&gt;AddOrder&lt;/em&gt; business method:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;public virtual void AddOrder(string referenceNumber)
{
    var order = new Order(this, referenceNumber);

    _orders.Add(order);

    DomainEvents.Raise(new OrderAddedEvent { Order = order });
}&lt;/pre&gt;

&lt;p&gt;Once the order has been created correctly we create a new instance of &lt;em&gt;OrderAddedEvent&lt;/em&gt; and set its &lt;em&gt;Order&lt;/em&gt; property to be the new instance. We then pass this to the static &lt;em&gt;Raise&lt;/em&gt; method. This method uses the StructureMap container to find handlers that can handle the event and invokes each of them passing them the event instance.&lt;/p&gt;

&lt;p&gt;If you invoke the Avernus Store sample you will get output something like:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/Windows-Live-Writer/c77831dcf33f_1219E/image_2.png" rel="lightbox"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/Windows-Live-Writer/c77831dcf33f_1219E/image_thumb.png" width="687" height="403" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What we can see here is that the output of the event handler (which prints the Order reference ABC012345) runs before NHibernate persists the new changes. This is important as it shows that the event handlers are running within the bounds of the transaction being used for the business method. As such other actions (such as sending transactional messages) may participate in that transaction. Additionally any failure in the event handler will cause the transaction to roll back. Event handlers should be written with this consideration in mind.&lt;/p&gt;

&lt;p&gt;Although handlers are requested from the container it is also possible to register them manually. This feature permits scenarios where configuring a container is undesirable, that is to say testing. The &lt;em&gt;DomainEvents&lt;/em&gt; type has a static method &lt;em&gt;Register&lt;/em&gt; that can be used to add event handlers directly. The &lt;em&gt;ClearCallbacks&lt;/em&gt; method is used to clear these added handlers to maintain test isolation.&lt;/p&gt;

&lt;p&gt;The primary implementation difference between the version in Avernus and Udi Dahan’s original is that the Avernus version is (as per the rest of Avernus) tied to StructureMap. Additionally I have made the internals somewhat LINQier but this has no effect on the external interface.&lt;/p&gt;&lt;img src="http://abstractcode.com/abstractblog/aggbug/215.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Colin David Scott</dc:creator>
            <guid>http://abstractcode.com/abstractblog/archive/2011/02/08/avernus-framework-part-2-domain-events.aspx</guid>
            <pubDate>Tue, 08 Feb 2011 11:33:44 GMT</pubDate>
            <comments>http://abstractcode.com/abstractblog/archive/2011/02/08/avernus-framework-part-2-domain-events.aspx#feedback</comments>
            <wfw:commentRss>http://abstractcode.com/abstractblog/comments/commentRss/215.aspx</wfw:commentRss>
        </item>
        <item>
            <title>AbstractState: A small library for writing state engines</title>
            <category>C#</category>
            <category>Development Tools</category>
            <link>http://abstractcode.com/abstractblog/archive/2011/02/08/abstractstate-a-small-library-for-writing-state-engines.aspx</link>
            <description>&lt;p&gt;Some time ago I was experimenting with simple fluent APIs. One of the things I produced while doing so is a small library for building simple state engines which I call AbstractState. This library is &lt;a href="https://github.com/ColinScott/AbstractState"&gt;available of GitHub&lt;/a&gt; under an Apache 2.0 licence.&lt;/p&gt;  &lt;p&gt;There are many cases where a full-blown workflow engine is impractical or undesirable but a simple state engine will nicely address the problem at hand. AbstractState addresses many of these cases by providing a simple mechanism to define and execute the permitted state transitions for a given type. The following example configures the permissible transitions for a type:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;StateManager.Initialise(initialise =&amp;gt; initialise.Add&amp;lt;Simple, SimpleState&amp;gt;()
    .GetStateWith(instance =&amp;gt; instance.State)
    .SetStateWith((instance, state) =&amp;gt; instance.SetState(state))
    .AllowTransition(SimpleState.First, new[] {SimpleState.Second, SimpleState.Fourth})
    .AllowTransition(SimpleState.Second, new[] {SimpleState.First, SimpleState.Third})
    .AllowTransition(SimpleState.Third, new[] {SimpleState.First, SimpleState.Third}));&lt;/pre&gt;

&lt;p&gt;This configuration starts with the &lt;em&gt;Initialise&lt;/em&gt; method on the static &lt;em&gt;StateManager&lt;/em&gt; class. &lt;em&gt;StateManager&lt;/em&gt; is the primary gateway to the library. It is static because the expected use cases have the library embedded in domain classes and other locations where use of a DI container is awkward or impractical.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Initialise&lt;/em&gt; takes a delegate of type &lt;em&gt;Action&amp;lt;IConfigurationExpression&amp;gt; &lt;/em&gt;that is used to define all the state transitions. For simplicity currently &lt;em&gt;Initialise&lt;/em&gt; clears any existing configuration when invoked. IConfigurationExpession contains a single method &lt;em&gt;Add&amp;lt;Stateful, State&amp;gt;&lt;/em&gt; which is used to define the state transitions for a single type.&lt;/p&gt;

&lt;p&gt;The example above shows the configuration of a type &lt;em&gt;Simple&lt;/em&gt;. The current state of a Simple instance is defined by the state type &lt;em&gt;SimpleState&lt;/em&gt;. This type may be anything that can be reliably used as a key for a collection. Strings and enums are typical although this is not mandatory. Caution should be exercised with reference types such that distinct instances that represent the same value are considered equal. In this example SimpleState is an enum.&lt;/p&gt;

&lt;p&gt;The Add method returns &lt;em&gt;IStatefulConfigurationExpression&amp;lt;TStateful, TState&amp;gt;&lt;/em&gt; that defines a number of methods used to define the permitted transitions. This interface also defines the &lt;em&gt;GetStateWith&lt;/em&gt; and &lt;em&gt;SetStateWith&lt;/em&gt; methods. These methods are the mechanism through which the retrieval and update of state against an instance are defined. This means that the stateful type does not need to implement any particular interface or mechanism in order to be integrated with the state engine. In this case the state is retrieved directly from the state property and is set using a helper method (&lt;em&gt;SetState&lt;/em&gt;) that is defined on the stateful class.&lt;/p&gt;

&lt;p&gt;Once we have defined how the state engine may interact with the stateful type’s state we specify the supported transactions. AbstractState works on a whitelist model where only state transitions that are explicitly valid are permitted. Here we specify six possible transitions using the &lt;em&gt;AllowTransition&lt;/em&gt;, two each for each of the First, Second and Third states. What we see here is that is possible to transition into a state (Fourth) for which there is no defined outgoing transitions. This is valid for end states which may never be exited.&lt;/p&gt;

&lt;p&gt;There are two overloads provided for &lt;em&gt;AllowTransition&lt;/em&gt;:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;IStatefulConfigurationExpression&amp;lt;TStateful, TState&amp;gt; AllowTransition(TState initial, params TState[] finalStates);
IStatefulConfigurationExpression&amp;lt;TStateful, TState&amp;gt; AllowTransition(TState initial, TState final, Func&amp;lt;TStateful, bool&amp;gt; checkFunction);&lt;/pre&gt;

&lt;p&gt;The first overload sets up simple transitions where the transition from the initial state to the final state(s) are always allowed. The second overload supports cases where the state transition may only be permitted under some circumstances. It takes a delegate of type &lt;em&gt;Func&amp;lt;TStateful, bool&amp;gt;&lt;/em&gt; to make this determination. If the return value of this delegate is false when passed an instance of the stateful type then the desired transition will not occur.&lt;/p&gt;

&lt;p&gt;Once the state manager has been configured it is simple to invoke:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;StateManager.Transition(instance, SimpleState.Third);&lt;/pre&gt;

&lt;p&gt;This code will perform one of two actions. If the configuration currently allows &lt;em&gt;instance&lt;/em&gt; to be put into the &lt;em&gt;Third&lt;/em&gt; state then the &lt;em&gt;SetStateWith&lt;/em&gt; delegate will be invoked to assign &lt;em&gt;instance&lt;/em&gt; to this state. If this is not permitted then the Transition method will throw &lt;em&gt;InvalidOperationException&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Anyone familiar with the StructureMap configuration API may realise that it is one of the primary influences on this API. This is unsurprising as the configuration API is one of my favourite StructureMap features.&lt;/p&gt;

&lt;p&gt;I’m reasonably happy with how this turned out as an experiment in fluent APIs. A potential future improvement is to allow the behaviour on an invalid transition to be configurable rather than simply throw &lt;em&gt;InvalidOperationException&lt;/em&gt;. I may look at this if there’s any interest in me doing so.&lt;/p&gt;&lt;img src="http://abstractcode.com/abstractblog/aggbug/214.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Colin David Scott</dc:creator>
            <guid>http://abstractcode.com/abstractblog/archive/2011/02/08/abstractstate-a-small-library-for-writing-state-engines.aspx</guid>
            <pubDate>Tue, 08 Feb 2011 09:15:57 GMT</pubDate>
            <comments>http://abstractcode.com/abstractblog/archive/2011/02/08/abstractstate-a-small-library-for-writing-state-engines.aspx#feedback</comments>
            <wfw:commentRss>http://abstractcode.com/abstractblog/comments/commentRss/214.aspx</wfw:commentRss>
        </item>
        <item>
            <title>Avernus Framework: Part 1 - Persistence</title>
            <category>Avernus</category>
            <category>Development Tools</category>
            <link>http://abstractcode.com/abstractblog/archive/2011/02/06/avernus-framework-part-1-persistence.aspx</link>
            <description>&lt;blockquote&gt;   &lt;p&gt;Index&lt;/p&gt;    &lt;p&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2011/02/06/avernus-framework-part-0-introduction.aspx"&gt;Part 0 – Introduction&lt;/a&gt;       &lt;br /&gt;Part 1 – Persistence      &lt;br /&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2011/02/08/avernus-framework-part-2-domain-events.aspx"&gt;Part 2 - Domain Events&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;A while back I watched &lt;a href="http://www.udidahan.com"&gt;Udi Dahan’s&lt;/a&gt; presentation on &lt;a href="http://www.infoq.com/presentations/Making-Roles-Explicit-Udi-Dahan"&gt;Making Roles Explicit&lt;/a&gt; and realised that it addressed a number of concerns with implementing and working with domain models that I didn’t even know I had. It’s rather awesome so I suggest you go watch it. I’ll wait.&lt;/p&gt;  &lt;p&gt;Based on these concepts Avernus seeks to provide:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The infrastructure to support a role interface based API for your domain model including: &lt;/li&gt;    &lt;li&gt;A simple abstraction to find and save role interfaces &lt;/li&gt;    &lt;li&gt;Default strategies for fetching and saving role interfaces that “just work” &lt;/li&gt;    &lt;li&gt;The ability to override the default strategies on a case-by-case basis in order to improve performance or adapt to client requirements. The substitution of strategies is transparent to the client API. &lt;/li&gt;    &lt;li&gt;The ability to raise events within the domain to allow access to additional services without attempting to perform injection or direct instantiation of dependencies inside the domain model. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;It should be noted that the Avernus Persistence infrastructure is intended only for executing business login in a domain. It is not intended to provide query access to data which should be handled separately.&lt;/p&gt;  &lt;h2&gt;Key Abstractions&lt;/h2&gt;  &lt;p&gt;For general usage of Avernus you only need to know a few key abstractions. These start with &lt;em&gt;IEntity&lt;/em&gt;, a marker interface that all role interfaces extend. Extending IEntity implies that an interface will:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Will provide one (and only one) business method that performs the action the role implies. &lt;/li&gt;    &lt;li&gt;May be fetched by the underlying infrastructure &lt;/li&gt;    &lt;li&gt;May be saved to the underlying infrastructure. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;A domain implementation of the role interface is provided. This is often a class mapped to the database by NHibernate but this is not mandatory. By providing appropriate fetching and saving strategies a non-mapped implementation may be used (although this type would be logically part of the domain). The client is not expected to (and is required not to) care about the implementation of the role interface with which it is provided. The client simply invokes the business method in order to perform the necessary business function. How this function is implemented is a concern of the implementer of the role interface not the client.&lt;/p&gt;  &lt;p&gt;The second key abstraction is the &lt;em&gt;IPersistenceFacade&lt;/em&gt; interface. This is provided to the client as their primary gateway into the system. It has two methods:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;em&gt;FindById&lt;/em&gt; is a method for locating a role interface based on a key. The nature of the key is defined by the role interface (as part of its implicit contract). The client should not care how the persistence facade obtains the instance it returns. &lt;/li&gt;    &lt;li&gt;&lt;em&gt;Save&lt;/em&gt; supports indicating to the infrastructure that the instance is to be persisted. It is a requirement that the client calls &lt;em&gt;Save&lt;/em&gt; after invoking the role interface’s business method. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;These two abstractions form the entirety of the API exposed to the client.&lt;/p&gt;  &lt;p&gt;Avernus uses strategies in order to fetch and save role interfaces. It provides default implementations that support the general usage case. The default fetching strategy simply requests the relevant mapped object from NHibernate with the supplied id as the primary key. The default saving strategy passes the role interface directly to the NHibernate ISession.Save() method. These implementations work in the general case but are not always ideal. In particular the fetching strategy loads dependent objects as per the NHibernate mapping configuration. This means that it may be loading either too much data (which is directly inefficient) or too little (which is inefficient when it is subsequently lazy loaded). Also you may wish to load a role interface based on something other than the mapped object primary key. To handle these scenarios the &lt;em&gt;IFetchingStrategy&amp;lt;T&amp;gt;&lt;/em&gt; is provided.&lt;/p&gt;  &lt;p&gt;By implementing &lt;em&gt;IFetchingStrategy&amp;lt;T&amp;gt;&lt;/em&gt; and registering it with the IoC container you are telling the infrastructure that you wish to be responsible for how a specific role interface is retrieved from the persistence store. The default implementation simply provides a type conversion so that a mapped type that NHibernate understands may be requested. A custom implementation may provide anything it likes so long as the result implements the requested role interface. In most cases it will execute a query against NHibernate specifying custom loading and/or a query other than by the primary ID. This allows more efficient retrieval of the information necessary to perform the specific business action. When implementing &lt;em&gt;IFetchingStrategy&amp;lt;T&amp;gt;&lt;/em&gt; it is the developers responsibility to ensure that the query is efficient.&lt;/p&gt;  &lt;p&gt;The fetching strategy is complemented by &lt;em&gt;ISavingStrategy&amp;lt;T&amp;gt;&lt;/em&gt; which handles persisting a role interface back into the persistence store. As with the fetching strategy there is a default implementation that handles most cases. However in some scenarios it is necessary to provide more information to NHibernate in order for it to operate efficiently or (in limited scenarios) at all. This may include explicitly calling Save on a child object so that NHibernate is not forced to query for its existence or handle the persistence of a non-mapped object constructed by a custom fetching strategy. Saving strategies are provided to the framework by registering an appropriate implementation of &lt;em&gt;ISavingStrategy&amp;lt;T&amp;gt;&lt;/em&gt; with the IoC container.&lt;/p&gt;  &lt;h2&gt;Domain Concepts&lt;/h2&gt;  &lt;p&gt;Using the Avernus Persistence infrastructure requires adherence to a few rules:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;All operations happen against a domain object. This impacts domain design as every business method must have an instance it can be executed against. This requires thinking about the context in which an initial interaction will operate. For instance in the example below adding a new customer occurs in the context of a Store, an existing domain construct that can implement the role interface. This does not necessarily need to be a mapped object if you are willing to write appropriate fetching and saving strategies. &lt;/li&gt;    &lt;li&gt;A role interface provides a single business method. This method gets passed everything required to perform the business action. The business logic is then executed in the domain. &lt;/li&gt;    &lt;li&gt;Role business methods do not return values. As they are often invoked in NServiceBus handlers in response to one-way messages they cannot assume that the client can do anything with a return value. &lt;/li&gt;    &lt;li&gt;The business method is invoked only a single time. If you need to invoke it multiple times then the role is incorrectly specified. &lt;/li&gt;    &lt;li&gt;All role interfaces must be saved to ensure that the appropriate save logic is executed. The client should not know the cases when automatic NHibernate behaviour means this is not required. Relying on such cases will introduce bugs if this should cease to be true in future. &lt;/li&gt;    &lt;li&gt;Clients are responsible for handling the NHibernate Session and any transaction to be used. When integrated with NServiceBus Avernus provides infrastructure to handle this automatically. For other uses the &lt;em&gt;StandaloneUnitOfWork&lt;/em&gt; class is provided (as seen in the example below) &lt;/li&gt; &lt;/ul&gt;  &lt;h2&gt;Sample&lt;/h2&gt;  &lt;p&gt;The Avernus source code (available at: &lt;a href="https://github.com/ColinScott/Avernus"&gt;&lt;font color="#0066cc"&gt;https://github.com/ColinScott/Avernus&lt;/font&gt;&lt;/a&gt;) includes a sample executable that demonstrates the usage of the Avernus Persistence infrastructure. Avernus Store is a simple console application that shows how the framework is used with a very simple domain model (in practice such a domain model is rather smaller than would generally warrant using Avernus).&lt;/p&gt;  &lt;p&gt;The &lt;em&gt;Domain&lt;/em&gt; namespace contains two role interfaces (&lt;em&gt;IAddCustomer&lt;/em&gt; and &lt;em&gt;ICreateOrder&lt;/em&gt;) that define business functions that the domain supports. It also includes the &lt;em&gt;CustomerDetails&lt;/em&gt; DTO that is used in the add customer API. The client uses only types in this namespace, it does not refer to or in any way use the mapped objects themselves.&lt;/p&gt;  &lt;p&gt;The &lt;em&gt;DomainObjects&lt;/em&gt; namespace is where we find the mapped objects (complete with mapping files, Fluent NHibernate support is pending). Here we see that &lt;em&gt;IAddCustomer&lt;/em&gt; is implemented on the &lt;em&gt;Store&lt;/em&gt; object. &lt;em&gt;Store&lt;/em&gt; is an aggregate root used as a context into which customers may be added. We create an initial store through the use of database scripts when the database is generated, this forms part of the basic system implementation. Additionally we see that &lt;em&gt;Order&lt;/em&gt; instances are created through &lt;em&gt;ICreateOrder&lt;/em&gt; which is a function of the &lt;em&gt;Customer&lt;/em&gt;.&lt;/p&gt;  &lt;p&gt;The &lt;em&gt;FetchingStrategies&lt;/em&gt; namespace is used to store a custom fetching strategy to be used with the &lt;em&gt;ICreateOrder&lt;/em&gt; role interface. This strategy changes the lookup of the mapped instance to be the customer name when using the &lt;em&gt;ICreateOrder&lt;/em&gt; role.&lt;/p&gt;  &lt;p&gt;The main Program class of the console application demonstrates setting up the Avernus infrastructure and some sample operations. It will also generate the store database (dropping any existing database) using Avernus infrastructure not described here.&lt;/p&gt;  &lt;p&gt;After the call to generate the database we start configuring Avernus (in practice you are unlikely to perform this configuration in the same class as you use to execute domain logic). We start with StructureMap configuration as shown:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;private static void ConfigureStructureMap()
{
    ObjectFactory.Initialize(initialise =&amp;gt;
        {
            initialise.AddRegistry&amp;lt;CoreRegistry&amp;gt;();
            initialise.AddRegistry&amp;lt;PersistenceDomainRegistry&amp;gt;();

            initialise.For&amp;lt;IPersistenceConfiguration&amp;gt;()
                .Use((IPersistenceConfiguration) ConfigurationManager.GetSection("persistence"));
            initialise.For&amp;lt;IPersistenceConfigurator&amp;gt;()
                .Singleton()
                .Use&amp;lt;PersistenceConfigurator&amp;lt;MsSql2008Dialect, SqlClientDriver&amp;gt;&amp;gt;();
            initialise.For&amp;lt;IContextStrategy&amp;lt;ISession&amp;gt;&amp;gt;()
                .Use&amp;lt;ThreadStaticContextStrategy&amp;lt;ISession&amp;gt;&amp;gt;();
            initialise.For&amp;lt;ISession&amp;gt;().Use(context =&amp;gt; context.GetInstance&amp;lt;IContextStrategy&amp;lt;ISession&amp;gt;&amp;gt;().Retrieve());

            initialise.Scan(scan =&amp;gt;
                {
                    scan.TheCallingAssembly();
                    scan.ConnectImplementationsToTypesClosing(typeof(IFetchingStrategy&amp;lt;&amp;gt;));
                });
        });
}&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;To start with we add the relevant Avernus registries. CoreRegistry comes from the base Avernus library and performs registration of some low level components. PersistenceDomainRegistry registers the persistence specific components that are common to all usages.&lt;/p&gt;

&lt;p&gt;Once we have done this we instruct StructureMap on how to locate the persistence configuration. We then register the &lt;em&gt;PersistenceConfigurator&amp;lt;TDialect, TDriver&amp;gt;&lt;/em&gt; class. By specifying the appropriate type parameters here you can control which NHibernate dialect and driver classes to use. This prevents Avernus from being tied to any specific database. This configuration is specified in code as Avernus is not intended for systems which must select their database at deployment time. You can include conditional logic to register the appropriate classes if you wish but this scenario is not officially supported.&lt;/p&gt;

&lt;p&gt;Next we register the context strategy used to hold session information. &lt;em&gt;IContextStrategy&amp;lt;T&amp;gt;&lt;/em&gt; is an abstraction that hides the context mechanism (call context, thread local, ASP.NET etc.) from client code. Here we specify that we are using a thread local strategy.&lt;/p&gt;

&lt;p&gt;The registration for &lt;em&gt;ISession&lt;/em&gt; is necessary when executing outside the NServiceBus support (which has alternate infrastructure for this case). In this case we specify that the current context strategy should be retrieved and the session loaded from it.&lt;/p&gt;

&lt;p&gt;Finally we scan the current assembly looking for anything that closes the open &lt;em&gt;IFetchingStrategy&amp;lt;&amp;gt;&lt;/em&gt; generic type. This handles detection of any fetching strategies and their automatic registration. An additional call to &lt;em&gt;ConnectImplementationsToTypesClosing&lt;/em&gt; can be made to handle &lt;em&gt;ISavingStrategy&amp;lt;T&amp;gt;&lt;/em&gt; if it is being used.&lt;/p&gt;

&lt;p&gt;After registering the relevant types with StructureMap we configure Avernus. This is done using:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;private static void ConfigureInfrastructure()
{
    ObjectFactory.GetInstance&amp;lt;IPersistenceConfigurator&amp;gt;()
        .ConfigurePersistence(new[] {typeof(Store).Assembly});
    ObjectFactory.GetInstance&amp;lt;IStrategyRegistrar&amp;gt;().Register();
}&lt;/pre&gt;

&lt;p&gt;The first call creates the NHibernate ISessionFactory instance and configures it for use. The argument to this call is a list of assemblies that contain mapped objects. This supports scenarios where you want to pull in business logic from multiple assemblies (which is occasionally very useful). Subsequent to this we get an instance of &lt;em&gt;IStrategyRegistrar&lt;/em&gt; and invoke it. This causes the Avernus infrastructure to locate all the objects mapped by the previous call and to configure Avernus to use them (primarily by providing default strategies for them). The Avernus persistence layer is now ready to use. Personally I generally just copy most of this when starting a new project, the primary gotcha is ensuring that all the relevant assemblies are passed to the &lt;em&gt;ConfigurePersistence&lt;/em&gt; method.&lt;/p&gt;

&lt;p&gt;Now that this is done we can do some work against the domain.&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;private static void RunExample()
{
    var customerId = Guid.NewGuid();

    var persistenceFacade = ObjectFactory.GetInstance&amp;lt;IPersistenceFacade&amp;gt;();

    using (var unitOfWork = new StandaloneUnitOfWork())
    {
        var addCustomer = persistenceFacade.FindById&amp;lt;IAddCustomer&amp;gt;("Avernus");

        addCustomer.AddCustomer(new CustomerDetails {CustomerId = customerId, Name = "New Customer"});

        persistenceFacade.Save(addCustomer);

        unitOfWork.Commit();
    }

    using (var unitOfWork = new StandaloneUnitOfWork())
    {
        var createOrder = persistenceFacade.FindById&amp;lt;ICreateOrder&amp;gt;("New Customer");

        createOrder.AddOrder("ABC012345");

        persistenceFacade.Save(createOrder);

        unitOfWork.Commit();
    }
}&lt;/pre&gt;

&lt;p&gt;This demonstrates creating a customer then adding an order to a customer. To start we generate a customer ID. This is necessary in scenarios where the client must know an identifier so that they may perform additional actions. Depending on scenario you may wish to use an alternate reference number with business significance.&lt;/p&gt;

&lt;p&gt;Next we obtain an instance of &lt;em&gt;IPersistenceFacade&lt;/em&gt;. This interface is stateless and the implementation may be reused. Alternately you may request a new instance if tracking it is undesirable.&lt;/p&gt;

&lt;p&gt;Once we have these resources we create an instance of &lt;em&gt;StandaloneUnitOfWork&lt;/em&gt;. This type is specific to cases where the code is not running in the context of another framework and is not used in scenarios such as NServiceBus integration. It encapsulates the creation of the &lt;em&gt;ISession&lt;/em&gt; instance and its registration in the context as well as the creation of a transaction. The instance is disposable and handles committing the transaction when it is itself disposed.&lt;/p&gt;

&lt;p&gt;Next comes the actual usage of Avernus. We request an implementation of &lt;em&gt;IAddCustomer&lt;/em&gt; from the persistence facade specifying a store of “Avernus” (often this identifier will be carried on an incoming message). We then invoke the business method to create the actual customer passing in a &lt;em&gt;CustomerDetails&lt;/em&gt; instance with the relevant data. This is followed by the &lt;em&gt;Save&lt;/em&gt; call to ensure the information is persisted.&lt;/p&gt;

&lt;p&gt;Lastly in the unit of work we call its &lt;em&gt;Commit&lt;/em&gt; method. This flags that the operation completed successfully so that we know to commit and not roll back the transaction of dispose. If this method is not called we assume that an exception was thrown somewhere in the operation. This prevents us having to do nasty and inefficient detection of whether the current thread is in an exception inside the &lt;em&gt;StandaloneUnitOfWork&lt;/em&gt; dispose method.&lt;/p&gt;

&lt;p&gt;We then repeat this pattern using the &lt;em&gt;ICreateOrder&lt;/em&gt; role interface. In this example the identifier passed to &lt;em&gt;FindById&lt;/em&gt; is the customer name. Avernus will automatically used the previously registered fetching strategy in this case in order to obtain the customer by the correct property. This is not visible to the client code which differs only in the interface used and therefore the name and parameters of the business method invoked.&lt;/p&gt;

&lt;h2&gt;What’s Next&lt;/h2&gt;

&lt;p&gt;Often in response to business logic we will wish to perform actions against external dependencies. This includes invoking services, sending messages and similar. Injecting dependencies into domain objects is complex and fragile. The next post in this series will describe the domain event capabilities Avernus provides to allow external interaction without polluting the domain model.&lt;/p&gt;&lt;img src="http://abstractcode.com/abstractblog/aggbug/213.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Colin David Scott</dc:creator>
            <guid>http://abstractcode.com/abstractblog/archive/2011/02/06/avernus-framework-part-1-persistence.aspx</guid>
            <pubDate>Sun, 06 Feb 2011 07:16:03 GMT</pubDate>
            <comments>http://abstractcode.com/abstractblog/archive/2011/02/06/avernus-framework-part-1-persistence.aspx#feedback</comments>
            <wfw:commentRss>http://abstractcode.com/abstractblog/comments/commentRss/213.aspx</wfw:commentRss>
        </item>
        <item>
            <title>In support of Marker Interfaces</title>
            <category>C#</category>
            <category>Development Tools</category>
            <link>http://abstractcode.com/abstractblog/archive/2011/02/06/in-support-of-marker-interfaces.aspx</link>
            <description>&lt;p&gt;One of the rules in Microsoft’s FxCop static code analysis tool suggests that you should avoid empty interfaces. From &lt;a href="http://msdn.microsoft.com/en-us/library/ms182128.aspx"&gt;MSDN&lt;/a&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Interfaces define members that provide a behavior or usage contract. The functionality that is described by the interface can be adopted by any type, regardless of where the type appears in the inheritance hierarchy. A type implements an interface by providing implementations for the members of the interface. An empty interface does not define any members. Therefore, it does not define a contract that can be implemented.&lt;/p&gt;    &lt;p&gt;If your design includes empty interfaces that types are expected to implement, you are probably using an interface as a marker or a way to identify a group of types. If this identification will occur at run time, the correct way to accomplish this is to use a custom attribute. Use the presence or absence of the attribute, or the properties of the attribute, to identify the target types. If the identification must occur at compile time, then it is acceptable to use an empty interface.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;I’m going to call this rule out as fundamentally wrong. There are many scenarios both at compile time and at runtime where determining that an instance implements a marker interface is of great value. To suggest that using an attribute is the “correct” way to make identifications at runtime is a sweeping statement that cannot be supported. Further there is a reliance here that the exceptions will be considered when evaluating the rule. Unfortunately it is all too common (and I myself have been guilty of this) of taking the tool pronouncement without question and these details will be lost. As a result designs that are entirely valid solutions will be degraded for no good reason.&lt;/p&gt;  &lt;p&gt;There seems to be an assumption in the above that the contract of an interface is only that which is explicitly specified in terms of its members. This assumption is clearly false. Almost every possible interface has implicit contracts that are not directly expressed in the code. For instance the &lt;a href="http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx"&gt;IDisposable.Dispose()&lt;/a&gt; method has an implicit contract that it will not throw if invoked multiple times (&lt;a href="http://abstractcode.com/abstractblog/archive/2009/03/12/todayrsquos-nitpicking-of-the-.net-bcl.aspx"&gt;not that Microsoft themselves always follow this contract&lt;/a&gt;). This contract is not expressed directly on the interface as C# provides no way to do so. Yet it exists. I see no legitimate reason to deny that the contract of an interface may be entirely implicit provided it is done in a considered fashion.&lt;/p&gt;  &lt;p&gt;It is entirely legitimate that at runtime I may wish to test if an instance adheres to a contract implicitly defined by an interface. This could be done with an attribute but dealing with attributes is inherently more complex. Further attributes cannot be considered compile time in constructs such as generics. If I wish to make decisions at both compile time and runtime or even to not unnecessarily close off the possibility a marker interface is the only possible choice. If I chose an attribute and later wish to do compile time checking them I would need to perform a significant refactoring (which may not be possible if my API has already been published).&lt;/p&gt;  &lt;p&gt;Attributes of course do have usages that interfaces (marker or otherwise) do not. An interface cannot be used at anything but the type level, attributes may be attached to almost anything. Attributes may also carry usage specific data and provide behaviour. If you need these capabilities then your choice is clear. Personally I find APIs that require these usages to be on the whole difficult and obscure to work with an extend (with some notable exceptions such as parameterised tests in MbUnit). However they are useful (if overused) capabilities that are worth considering.&lt;/p&gt;  &lt;p&gt;In summary: FxCop is wrong, Marker Interfaces rock. Go forth and disable rule CA1040 immediately.&lt;/p&gt;&lt;img src="http://abstractcode.com/abstractblog/aggbug/212.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Colin David Scott</dc:creator>
            <guid>http://abstractcode.com/abstractblog/archive/2011/02/06/in-support-of-marker-interfaces.aspx</guid>
            <pubDate>Sun, 06 Feb 2011 05:38:01 GMT</pubDate>
            <comments>http://abstractcode.com/abstractblog/archive/2011/02/06/in-support-of-marker-interfaces.aspx#feedback</comments>
            <wfw:commentRss>http://abstractcode.com/abstractblog/comments/commentRss/212.aspx</wfw:commentRss>
        </item>
        <item>
            <title>Avernus Framework: Part 0 - Introduction</title>
            <category>Avernus</category>
            <link>http://abstractcode.com/abstractblog/archive/2011/02/06/avernus-framework-part-0-introduction.aspx</link>
            <description>&lt;p&gt;Although no one seems to be able to come up with a name that makes everyone happy a .NET community exists and it produces some very nice tools. Properly utilised I believe these frameworks allow .NET developers the ability to write applications the equal of those on any other platform. Avernus is not an attempt to add another entry to this list. Rather it encapsulates one approach to using some of my preferred frameworks together. Most of the magic it provides is borrowed but I present this in the hope that someone will find my small additions helpful. (Does this sound sufficiently modest? I’m not sure).&lt;/p&gt;  &lt;p&gt;Avernus is focused around three key frameworks:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="https://github.com/structuremap/structuremap"&gt;StructureMap&lt;/a&gt; for Dependency Injection &lt;/li&gt;    &lt;li&gt;&lt;a href="http://nhforge.org/"&gt;NHibernate&lt;/a&gt; for Object Relational Mapping &lt;/li&gt;    &lt;li&gt;&lt;a href="http://nservicebus.com/"&gt;NServiceBus&lt;/a&gt; as the communication paradigm &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Avernus also ties in:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://automapper.codeplex.com/"&gt;AutoMapper&lt;/a&gt; for object-object mapping &lt;/li&gt;    &lt;li&gt;&lt;a href="http://fluentvalidation.codeplex.com/"&gt;Fluent Validation&lt;/a&gt; for object validation support &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Key features:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Providing the ability to deal with domain objects as roles, based on &lt;a href="http://www.udidahan.com/"&gt;Udi Dahan’s&lt;/a&gt; presentation on &lt;a href="http://www.infoq.com/presentations/Making-Roles-Explicit-Udi-Dahan"&gt;Making Roles Explicit&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;Opinionated integration of above into NServiceBus. &lt;/li&gt;    &lt;li&gt;Glue to join Fluent Validation and NServiceBus together &lt;/li&gt;    &lt;li&gt;Abstractions for supporting contexts in various environments &lt;/li&gt;    &lt;li&gt;Abstractions making it easier to define AutoMapper mappings in multiple locations &lt;/li&gt;    &lt;li&gt;Various low level helper code I find it useful to have available &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Avernus itself is licenced under an Apache 2.0 Licence. The included frameworks have their own licencing terms. In particular note that NServiceBus requires licencing for most production use. See the individual processes or included licence files for more information. Full source code can be found on &lt;a href="https://github.com/"&gt;GitHub&lt;/a&gt; at &lt;a href="https://github.com/ColinScott/Avernus"&gt;https://github.com/ColinScott/Avernus&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Once you have used your favourite Git client to obtain the source code (or downloaded a source zip from GitHub) the build process is straightforward. Open a Visual Studio 2010 command prompt and change directory to the Avernus base directory. Then run &lt;em&gt;Package.bat&lt;/em&gt; to build and test Avernus and generate a zip file containing the binaries and their dependencies (located in the Package directory).&lt;/p&gt;  &lt;p&gt;The posts that follow will describe the capabilities of Avernus.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Index&lt;/p&gt;    &lt;p&gt;Part 0 – Introduction      &lt;br /&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2011/02/06/avernus-framework-part-1-persistence.aspx"&gt;Part 1 – Persistence&lt;/a&gt;      &lt;br /&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2011/02/08/avernus-framework-part-2-domain-events.aspx"&gt;Part 2 - Domain Events&lt;/a&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;img src="http://abstractcode.com/abstractblog/aggbug/211.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Colin David Scott</dc:creator>
            <guid>http://abstractcode.com/abstractblog/archive/2011/02/06/avernus-framework-part-0-introduction.aspx</guid>
            <pubDate>Sun, 06 Feb 2011 03:46:40 GMT</pubDate>
            <comments>http://abstractcode.com/abstractblog/archive/2011/02/06/avernus-framework-part-0-introduction.aspx#feedback</comments>
            <wfw:commentRss>http://abstractcode.com/abstractblog/comments/commentRss/211.aspx</wfw:commentRss>
        </item>
        <item>
            <title>On the handling of errors</title>
            <category>C#</category>
            <category>Development Practices</category>
            <category>Web Development</category>
            <link>http://abstractcode.com/abstractblog/archive/2011/02/05/on-the-handling-of-errors.aspx</link>
            <description>&lt;p&gt;I was asked recently if errors in an application should be handled in the business layer or in the UI. The answer to this is simple: Neither. Doing so is repetitive and unproductive. Error handling should be an automatic part of your infrastructure.&lt;/p&gt;  &lt;p&gt;It may seem that error handling is not something that can be performed automatically. But this is due to a broader definition of error than is applicable here. Conditions that are expected and probable during your applications execution are not errors, they’re use cases. If may be a user error that they have entered an invalid value, or a network issue that causes your web browser to be unable to contact a website. But these are expected conditions that an application must deal with. Your application stack should have a clean way of reporting that requested operations could not be completed and this should be tested appropriately.&lt;/p&gt;  &lt;p&gt;A genuine application error is caused by coding errors or violations of fundamental assumptions that your application works with. If your validation code allows an out of range value that causes a divide by zero this is an application error. If you cannot find an essential application file this is an application error. Such an error will almost certainly result in an exception. Handling these exceptions in the business specific code is not helpful. You can’t anticipate these errors as you would otherwise have prevented them. Placing duplicate error handling code throughout your codebase is a maintenance overhead and does not really provide any value. Instead the framework on which you build your application should handle these cases.&lt;/p&gt;  &lt;p&gt;If you are building a web application on ASP.NET (including ASP.NET MVC) then ELMAH is an excellent tool for providing this functionality: &lt;a href="http://code.google.com/p/elmah/"&gt;&lt;font color="#0066cc"&gt;http://code.google.com/p/elmah/&lt;/font&gt;&lt;/a&gt;. Many GUI application frameworks will provide the ability to handle errors or you can hook into the AppDomain events invoked on unhandled exceptions. In a service process some simple dynamic proxies coupled with dependency injection can wrap exception handling logic around every service invocation without requiring any modification of the business code. Some frameworks such as the NServiceBus Host provide logging capabilities built in that require only configuration.&lt;/p&gt;  &lt;p&gt;What we are aiming for therefore is that handling of genuine errors in the application is automatic and comprehensive. This is not possible if we start polluting our business or UI code with attempts to handle the unhandleable. Build your application so that this handling happens so transparently in the background that you can generally forget its even there.&lt;/p&gt;&lt;img src="http://abstractcode.com/abstractblog/aggbug/210.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Colin David Scott</dc:creator>
            <guid>http://abstractcode.com/abstractblog/archive/2011/02/05/on-the-handling-of-errors.aspx</guid>
            <pubDate>Sat, 05 Feb 2011 01:00:32 GMT</pubDate>
            <comments>http://abstractcode.com/abstractblog/archive/2011/02/05/on-the-handling-of-errors.aspx#feedback</comments>
            <wfw:commentRss>http://abstractcode.com/abstractblog/comments/commentRss/210.aspx</wfw:commentRss>
        </item>
        <item>
            <title>Giving C# a Times method</title>
            <category>C#</category>
            <link>http://abstractcode.com/abstractblog/archive/2010/08/14/giving-c-a-times-method.aspx</link>
            <description>&lt;p&gt;Want to be able to write code like “5.Times” but you can’t use a language like &lt;a href="http://www.ruby-lang.org/"&gt;Ruby&lt;/a&gt;? You can do this in C# with some extension method magic.&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;public static void Times(this int numberOfTimes, Action action)
{
    for (var number = 0; number &amp;lt; numberOfTimes; number++)
    {
        action();
    }
}&lt;/pre&gt;

&lt;p&gt;Now you can write code like:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;5.Times(() =&amp;gt; Console.WriteLine("Hello"));&lt;/pre&gt;

&lt;p&gt;Sometimes however you want to know the index of the invocation of the lambda. This can be done with:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;public static void Times(this int numberOfTimes, Action&amp;lt;int&amp;gt; action)
{
    for (var number = 0; number &amp;lt; numberOfTimes; number++)
    {
        action(number);
    }
}&lt;/pre&gt;

&lt;p&gt;This allows:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;3.Times(count =&amp;gt; Console.WriteLine(count));&lt;/pre&gt;

&lt;p&gt;These are nifty for invoking some kind of logic a specified number of times. But what if your action returns a result you’d like to collect? Try:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;public static IEnumerable&amp;lt;TResult&amp;gt; Times&amp;lt;TResult&amp;gt;(this int numberOfTimes, Func&amp;lt;int, TResult&amp;gt; func)
{
    for (var number = 0; number &amp;lt; numberOfTimes; number++)
    {
        yield return func(number);
    }
}&lt;/pre&gt;

&lt;p&gt;Rather than return void this returns an IEnumerable&amp;lt;T&amp;gt; that you can then use like so:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;var result = 4.Times(count =&amp;gt; count * count);&lt;/pre&gt;

&lt;p&gt;This &lt;a href="http://github.com/ColinScott/Avernus/blob/master/Main/Core/ActionExtensions.cs"&gt;code can be found&lt;/a&gt; in &lt;a href="http://github.com/ColinScott/Avernus"&gt;Avernus&lt;/a&gt;, but in most cases it’s probably more effective to copy it directly into your own project.&lt;/p&gt;&lt;img src="http://abstractcode.com/abstractblog/aggbug/209.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Colin David Scott</dc:creator>
            <guid>http://abstractcode.com/abstractblog/archive/2010/08/14/giving-c-a-times-method.aspx</guid>
            <pubDate>Sat, 14 Aug 2010 03:36:48 GMT</pubDate>
            <comments>http://abstractcode.com/abstractblog/archive/2010/08/14/giving-c-a-times-method.aspx#feedback</comments>
            <wfw:commentRss>http://abstractcode.com/abstractblog/comments/commentRss/209.aspx</wfw:commentRss>
        </item>
        <item>
            <title>StructureMap: Part 4 - Scanning</title>
            <category>StructureMap</category>
            <category>Development Practices</category>
            <link>http://abstractcode.com/abstractblog/archive/2010/07/03/structuremap-part-4-scanning.aspx</link>
            <description>&lt;blockquote&gt;   &lt;h6&gt;Index&lt;/h6&gt;    &lt;ul&gt;     &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/06/12/structuremap-part-0-introduction.aspx"&gt;Part 0 – Introduction&lt;/a&gt; &lt;/li&gt;      &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/06/12/structuremap-part-1-ndash-the-basics.aspx"&gt;Part 1 – The Basics&lt;/a&gt; &lt;/li&gt;      &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/06/13/structuremap-part-2-ndash-instance-lifecycles.aspx"&gt;Part 2 – Instance Lifecycles&lt;/a&gt; &lt;/li&gt;      &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/06/18/structuremap-part-3-ndash-constructing-the-concrete-type.aspx"&gt;Part 3 – Constructing the Concrete Type&lt;/a&gt;&lt;/li&gt;      &lt;li&gt;Part 4 - Scanning &lt;/li&gt;   &lt;/ul&gt; &lt;/blockquote&gt;  &lt;p&gt;So far I’ve shown enough to build a working DI system. By registering concrete types for your abstractions you can fully configure the container. However it’s unlikely to have escaped your notice that doing so is a not inconsequential amount of work in anything but small systems. StructureMap provides a solution to this in the form of auto registration.&lt;/p&gt;  &lt;p&gt;Auto registration takes advantage of the fact that the structure of most types that we wish to register in a container follows certain patterns or conventions. By taking advantage of these conventions we can locate and register types with the container without having to specify them individually. Further if we adhere to the conventions for new types they will be registered automatically without any additional work. This reduces our configuration to specification of the conventions and individual registration for those few types for which the conventions are inapplicable.&lt;/p&gt;  &lt;p&gt;We can start with one of the simplest and most common conventions. There are a wide variety of instances that adhere to the simple pattern of having a concrete class that implements an interface that shares the same name with the addition of the standard .NET &lt;em&gt;I&lt;/em&gt; prefix. This abstraction breaks the coupling between the implementation and anything that may use it but for most cases there is not a need to have multiple implementations of the abstraction. They are generally transient instances and any state they carry does not last between uses. A stateless service is a typical example.&lt;/p&gt;  &lt;p&gt;Consider an assembly that contains many services, among them &lt;em&gt;ExampleService&lt;/em&gt; which implements &lt;em&gt;IExampleService&lt;/em&gt;. Using auto registration we can locate and register into the StructureMap container all of these services that adhere to our convention. The code to do so will look like:&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:5099bfae-bf04-405d-8974-521fb93de139" class="wlWriterEditableSmartContent"&gt;&lt;pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"&gt;&lt;span style="color: #000000;"&gt;ObjectFactory.Initialize(initialise &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;
    {
        initialise.Scan(scan &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;
            {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
            });
    });
&lt;/span&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p&gt;This code utilises the type scanner to perform registration. The &lt;em&gt;Scan&lt;/em&gt; method takes a delegate (of type &lt;em&gt;Action&amp;lt;IAssemblyScanner&amp;gt;&lt;/em&gt;) for which we can supply a lambda. In the lambda we do two things. The first is instruct the scanner where it should be scanning. In this case we specify the assembly in which this code is located by invoking the method &lt;em&gt;TheCallingAssembly&lt;/em&gt;. The then tell StructureMap to apply its default conventions. The StructureMap default conventions are conveniently equivalent to the convention described above.&lt;/p&gt;

&lt;p&gt;This method may be used to register large numbers of types and is probably the most common usage of the scanner. It will cover most cases but the scanner is capable of significantly more than this. Let’s consider another convention. We have some kind of plug-in system where all plug-ins must implement a common interface. We’d like to register all of our plug-ins with the container but we won’t (and likely can’t) have the close correspondence between the name of the plug-in interface and that of the types that implement it. We can use another convention in the scanner to handle this for us. We can add a call to &lt;em&gt;AddAllTypesOf&amp;lt;T&amp;gt;&lt;/em&gt; to our scanner. This will cause it to register any class that implements the specified generic type. For an interface of type &lt;em&gt;IPlugin&lt;/em&gt; this would look like:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:6f475bc4-c711-4f31-85f2-b910a67d9c20" class="wlWriterEditableSmartContent"&gt;&lt;pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"&gt;&lt;span style="color: #000000;"&gt;ObjectFactory.Initialize(initialise &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;
    {
        initialise.Scan(scan &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;
            {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.AddAllTypesOf&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;IPlugin&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;();
            });
    });
&lt;/span&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p&gt;(We have kept the call to &lt;em&gt;WithDefaultConventions&lt;/em&gt; here but it is not necessary to register the &lt;em&gt;IPlugin&lt;/em&gt; implementations)&lt;/p&gt;

&lt;p /&gt;

&lt;p /&gt;

&lt;p&gt;This supports the case where &lt;em&gt;IPlugin&lt;/em&gt; is non-generic. We may also encounter situations where we wish to register anything that implements a generic interface. Let’s assume that for some (probably crazy) reason our system also has a plugin interface &lt;em&gt;IPlugin&amp;lt;T&amp;gt;&lt;/em&gt; for which we wish to register any implementations. StructureMap provides inbuilt support for this scenario using the &lt;em&gt;ConnectImplementationsToTypesClosing&lt;/em&gt; method.&lt;/p&gt;

&lt;p&gt;Before I show the code, a quick diversion through the basics of open and closed generic types. The type &lt;em&gt;IPlugin&amp;lt;T&amp;gt;&lt;/em&gt; is an open generic type for which the type parameter is not specified. We cannot (for all practical purposes) have an instance of this type as it is incomplete. We &lt;strong&gt;can&lt;/strong&gt; obtain the type itself using &lt;em&gt;typeof(IPlugin&amp;lt;&amp;gt;)&lt;/em&gt;. If we want an instance we must get a closed type for which the type parameters have been specified. &lt;em&gt;IPlugin&amp;lt;int&amp;gt;&lt;/em&gt; would be an example and we may treat this type for the most part as we would a non-generic type. We can through reflection determine the open generic type for a closed type and create a closed type from an open type. This is annoying and fortunately StructureMap handles it all for us. (We can also have partially closed types, but that’s outside the scope of this post)&lt;/p&gt;

&lt;p&gt;The code to register all the concrete classes that implement (and therefore close) our generic interface looks like:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:55e01b7c-7576-4b5e-b85e-659007c3b26a" class="wlWriterEditableSmartContent"&gt;&lt;pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"&gt;&lt;span style="color: #000000;"&gt;ObjectFactory.Initialize(initialise &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;
    {
        initialise.Scan(scan &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;
            {
                scan.TheCallingAssembly();
                scan.ConnectImplementationsToTypesClosing(&lt;/span&gt;&lt;span style="color: #0000FF;"&gt;typeof&lt;/span&gt;&lt;span style="color: #000000;"&gt;(IPlugin&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;));
            });
    });
&lt;/span&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;All of these examples scan the assembly in which the code itself resides. This is the most common option but there are cases where scanning of other assemblies may be desirable. This includes cases where you wish to register instances from an assembly you do not control and where you may wish to scan a directory for plug-in or extension assemblies that are unknown at compilation time. To handle these cases StructureMap provides a number of options other that &lt;em&gt;TheCallingAssembly&lt;/em&gt; for specifying where it should scan. These include:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;AssembliesFromApplicationBaseDirectory&lt;/strong&gt; scans every assembly in (surprisingly) the applications base directory. It has an overload that supports providing a filter to exclude assemblies if desired.&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;AssembliesFromPath&lt;/strong&gt; scans every assembly in the directory with the specified path. It also has an overload for providing a filter.&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;Assembly&lt;/strong&gt; takes an individual assembly to be scanned (as either an instance of the &lt;em&gt;Assembly&lt;/em&gt; type or by name)&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;AssemblyContainingType&lt;/strong&gt; supports determining the assembly to be scanned by specification of a type within the assembly (as either a type parameter or instance of the &lt;em&gt;Type&lt;/em&gt; class)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It is also possible to control how the scanner treats types within an assembly using Exclude or Include rules. Exclude rules allow patterns to be specified that will prevent any matching type from being registered. Any type matching one or more exclude rules will be ignored by the scanner:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Exclude&lt;/strong&gt; takes a filter delegate than allows individual types to be excluded from the scanner.&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;ExcludeNamespace&lt;/strong&gt; takes a string defining a namespace. The scanner will exclude all types in this namespace.&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;ExcludeNamespaceContainingType&lt;/strong&gt; has a type parameter. Any types sharing the namespace of the specified type will be excluded.&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;ExcludeType&lt;/strong&gt; takes a generic parameter. The specified type for this parameter will be excluded.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Include rules support patterns that all types to be registered must adhere to. A type must match at least one include rule to be registered:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Include&lt;/strong&gt; takes a filter delegate. Any type matching this filter will be included.&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;IncludeNamespace&lt;/strong&gt; takes a string defining a namespace. Any type in this namespace is included.&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;IncludeNamespaceContainingType&lt;/strong&gt; has a type parameter. Any type sharing a namespace with this type will be included.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Inside a single Scan invocation you should generally use either all Exclude or all Include statements.&lt;/p&gt;

&lt;p&gt;Scanning allows us to significantly simplify the configuration of the container. If you have a system with more than one assembly you may be thinking that you will need to specify the assemblies to scan or invoke StructureMap configuration manually inside each assembly. StructureMap provides a better mechanism for doing so in the form of Registries which will be the subject of the next post in this series.&lt;/p&gt;&lt;img src="http://abstractcode.com/abstractblog/aggbug/208.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Colin David Scott</dc:creator>
            <guid>http://abstractcode.com/abstractblog/archive/2010/07/03/structuremap-part-4-scanning.aspx</guid>
            <pubDate>Sat, 03 Jul 2010 01:43:22 GMT</pubDate>
            <comments>http://abstractcode.com/abstractblog/archive/2010/07/03/structuremap-part-4-scanning.aspx#feedback</comments>
            <wfw:commentRss>http://abstractcode.com/abstractblog/comments/commentRss/208.aspx</wfw:commentRss>
        </item>
        <item>
            <title>StructureMap: Part 3 &amp;ndash; Constructing the Concrete Type</title>
            <category>StructureMap</category>
            <category>Development Practices</category>
            <link>http://abstractcode.com/abstractblog/archive/2010/06/18/structuremap-part-3-ndash-constructing-the-concrete-type.aspx</link>
            <description>&lt;blockquote&gt;   &lt;h6&gt;Index&lt;/h6&gt;    &lt;ul&gt;     &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/06/12/structuremap-part-0-introduction.aspx"&gt;Part 0 – Introduction&lt;/a&gt; &lt;/li&gt;      &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/06/12/structuremap-part-1-ndash-the-basics.aspx"&gt;Part 1 – The Basics&lt;/a&gt; &lt;/li&gt;      &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/06/13/structuremap-part-2-ndash-instance-lifecycles.aspx"&gt;Part 2 – Instance Lifecycles&lt;/a&gt; &lt;/li&gt;      &lt;li&gt;Part 3 – Constructing the Concrete Type &lt;/li&gt;      &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/07/03/structuremap-part-4-scanning.aspx"&gt;Part 4 - Scanning&lt;/a&gt;&lt;/li&gt;   &lt;/ul&gt; &lt;/blockquote&gt;  &lt;p&gt;Now that we can control the lifecycle of an instance it’s worth considering how those instances are constructed. In the code shown so far the parameter-less &lt;em&gt;Use&lt;/em&gt; method is responsible for specifying the concrete type. Using this overload will cause StructureMap to create instances using the type constructor. This will cover many scenarios but there will be cases where you will need more control over how instances are constructed. For these scenarios StructureMap provides a number of overloads for &lt;em&gt;Use&lt;/em&gt;.&lt;/p&gt;  &lt;p&gt;The simplest scenario is that we wish the container to always supply an instance we already have. This is almost illegally simple:&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:dfe77a5f-0a3a-418d-8205-13b59a527cf7" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;var existingInstance = new ExistingInstance();
ObjectFactory.Initialize(initialise =&amp;gt;
	{
		initialise.For&amp;lt;IExistingInstance&amp;gt;().Use(existingInstance);
	});
&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;The container will now return the specified instance. This has an implication on the lifecycle. As we’ve specified the instance to return we get Singleton behaviour. To demonstrate the code:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:b7b59b02-4821-4029-ab7d-37228e184653" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;var firstExistingInstance = ObjectFactory.GetInstance&amp;lt;IExistingInstance&amp;gt;();
var secondExistingInstance = ObjectFactory.GetInstance&amp;lt;IExistingInstance&amp;gt;();

Console.WriteLine(string.Format("Existing instances are the same: {0}", ReferenceEquals(firstExistingInstance, secondExistingInstance)));
&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;Produces the output:&lt;/p&gt;

&lt;p&gt; &lt;a href="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/WindowsLiveWriter/StructureMapPart3ConstructingtheConcrete_C14/image_2.png" rel="lightbox"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/WindowsLiveWriter/StructureMapPart3ConstructingtheConcrete_C14/image_thumb.png" width="681" height="396" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;This is unlike the default behaviour when we specify the type not the instance where StructureMap will create a new instance for every call to GetInstance&amp;lt;T&amp;gt;. It is therefore important that any instance registered in the container in this fashion be threadsafe when used in a multi-threaded environment.&lt;/p&gt;

&lt;p&gt;Being able to use an existing instance is helpful but we will also have situations where we need to specify the mechanism used to construct a new instance. This allows us to use lifecycles other than Singleton as well as having control over instance construction. For this purpose StructureMap provides two overloads to &lt;em&gt;Use&lt;/em&gt; that take &lt;em&gt;Func&lt;/em&gt; delegates. By supplying a lambda or method to one of these overloads we can specify the code to be used to generate instances.&lt;/p&gt;

&lt;p&gt;The simpler method takes a &lt;em&gt;Func&amp;lt;T&amp;gt;&lt;/em&gt; (where &lt;em&gt;T&lt;/em&gt; is the plugin type). Its usage is straightforward:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:ea6d84d7-0904-4bce-95f4-b2b19fc2f081" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;initialise.For&amp;lt;IDynamicItem&amp;gt;().Use(() =&amp;gt; new DynamicItem());&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;We can also specify constructor parameters:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:16869437-7f52-41ac-a9ae-0f6abd1a67ad" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;initialise.For&amp;lt;IDynamicItem&amp;gt;().Use(() =&amp;gt; new DynamicItem("Some Parameter"));&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;Or a method that matches the &lt;em&gt;Func&amp;lt;T&amp;gt;&lt;/em&gt; signature:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:d5657d6d-26f2-41ef-acff-3cd8a7548e4f" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;initialise.For&amp;lt;IDynamicItem&amp;gt;().Use(DynamicItemFactory.CreateItem);&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;In short we can do all the normal things that are supported for &lt;em&gt;Func&amp;lt;T&amp;gt;&lt;/em&gt; arguments to a method.&lt;/p&gt;

&lt;p&gt;The more complex method takes a &lt;em&gt;Func&amp;lt;IContext, T&amp;gt;&lt;/em&gt; and is useful for scenarios where the construction process needs to consider the context in which the instance is being created. This is useful for advanced scenarios that will be described later in this series. However I will note here that &lt;em&gt;IContext&lt;/em&gt; supports &lt;em&gt;GetInstance&amp;lt;T&amp;gt;&lt;/em&gt; making this the overload to use when you are manually constructing an instance that has dependencies you wish to obtain from the container. For example:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:c5382b06-ba01-4f1f-8fab-adb1e002c0c2" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;initialise.For&amp;lt;IDependentDynamicItem&amp;gt;().Use(context =&amp;gt; new DependentDynamicItem(context.GetInstance&amp;lt;IDynamicItem&amp;gt;()));&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;Before this part of the series ends it’s worth considering the behaviour of the standard parameter-less &lt;em&gt;Use&lt;/em&gt; method we’d been using prior to this article. This overload causes StructureMap to use a constructor on the type to create instances. If there is only a single constructor then it is obvious which constructor to use. However things are not always this simple. There are a few things to consider in how StructureMap selects the constructor to use.&lt;/p&gt;

&lt;p&gt;The first thing to note is that StructureMap will only consider public constructors. A type with no public constructors cannot be handled and will result in a &lt;em&gt;StructureMapException&lt;/em&gt;. If you need to use a type with no public constructors with StructureMap then you must use the &lt;em&gt;Use&lt;/em&gt; overloads discussed in this post.&lt;/p&gt;

&lt;p&gt;Of the public constructors StructureMap will pick that which has the most arguments. This is done on the general assumption that the constructor with the most arguments will supply the greatest number of dependencies to the instance. In the event that there are multiple constructors that match this criteria StructureMap will pick the first it encounters. In such scenarios it is probably best to eliminate the excess constructors in order to ensure certainty and reduce confusion. Where this is not possible (for instance if the type is supplied by an external library) taking over construction using a Use overload as described above should be seriously considered. The alternative is to rely on behaviour that is liable to change if StructureMap, the external library are updated.&lt;/p&gt;

&lt;p&gt;Now that we can control both the construction and lifecycle of instances the next post in this series will describe how we can make most of the configuration we’ve done so far unnecessary.&lt;/p&gt;&lt;img src="http://abstractcode.com/abstractblog/aggbug/207.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Colin David Scott</dc:creator>
            <guid>http://abstractcode.com/abstractblog/archive/2010/06/18/structuremap-part-3-ndash-constructing-the-concrete-type.aspx</guid>
            <pubDate>Thu, 17 Jun 2010 14:53:27 GMT</pubDate>
            <comments>http://abstractcode.com/abstractblog/archive/2010/06/18/structuremap-part-3-ndash-constructing-the-concrete-type.aspx#feedback</comments>
            <wfw:commentRss>http://abstractcode.com/abstractblog/comments/commentRss/207.aspx</wfw:commentRss>
        </item>
        <item>
            <title>StructureMap: Part 2 &amp;ndash; Instance Lifecycles</title>
            <link>http://abstractcode.com/abstractblog/archive/2010/06/13/structuremap-part-2-ndash-instance-lifecycles.aspx</link>
            <description>&lt;blockquote&gt;   &lt;h6&gt;Index&lt;/h6&gt;    &lt;ul&gt;     &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/06/12/structuremap-part-0-introduction.aspx"&gt;Part 0 – Introduction&lt;/a&gt; &lt;/li&gt;      &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/06/12/structuremap-part-1-ndash-the-basics.aspx"&gt;Part 1 – The Basics&lt;/a&gt; &lt;/li&gt;      &lt;li&gt;Part 2 – Instance Lifecycles &lt;/li&gt;      &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/06/18/structuremap-part-3-ndash-constructing-the-concrete-type.aspx"&gt;Part 3 – Constructing the Concrete Type&lt;/a&gt;&lt;/li&gt;      &lt;li&gt;&lt;a href="http://abstractcode.com/abstractblog/archive/2010/07/03/structuremap-part-4-scanning.aspx"&gt;Part 4 - Scanning&lt;/a&gt;  &lt;/li&gt;   &lt;/ul&gt; &lt;/blockquote&gt;  &lt;p&gt;So far I’ve shown how to do basic registration. This will let the container know of the type so that it will try to create it. This registration gives us the defaults that StructureMap assumes unless it is told otherwise. These defaults are reasonable for most types but they’re not always applicable. This post describes some of the options StructureMap provides for controlling how the container manages the lifecycle of instances.&lt;/p&gt;  &lt;p&gt;By default StructureMap constructs instances transiently. Each time the instance is requested from the container a new instance is constructed and returned to the controller. We can demonstrate this with the following code snippet:&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:c1f7f99c-e3e5-4fcb-b96c-0c1e9734c205" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;ObjectFactory.Initialize(initialise =&amp;gt;
	{
		initialise.For&amp;lt;ITransientService&amp;gt;().Use&amp;lt;TransientService&amp;gt;();
	});

var firstTransientService = ObjectFactory.GetInstance&amp;lt;ITransientService&amp;gt;();
var secondTransientService = ObjectFactory.GetInstance&amp;lt;ITransientService&amp;gt;();

Console.WriteLine(string.Format("Transient instances are the same: {0}",
	ReferenceEquals(firstTransientService, secondTransientService)));
&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;When we run this we get the following output:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/WindowsLiveWriter/StructureMapPart2RegistrationOptions_9E19/image_6.png" rel="lightbox"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/WindowsLiveWriter/StructureMapPart2RegistrationOptions_9E19/image_thumb_2.png" width="681" height="396" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p /&gt;

&lt;p /&gt;

&lt;p&gt;In general this is not an issue. Most types managed by StructureMap do not need to carry state between operations, and the construction of lightweight transient objects in .NET is very cheap. Unfortunately this doesn’t apply to all types. There are circumstances where we need to maintain state potentially across many operations. Some types are expensive to construct such that for performance reasons it simply isn’t feasible to keep creating new instances. Types may also wrap limited resources such that we may not be able to construct new instances if existing instances already exist. For this reason StructureMap supports lifecycles.&lt;/p&gt;

&lt;p&gt;The lifecycle controls when new instances are created and how StructureMap maintains references to the. The transient default specifies that a new instance is created per request and that StructureMap will not track the instance. Additionally StructureMap provides the following lifecycles:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Singleton &lt;/li&gt;

  &lt;li&gt;Thread Local &lt;/li&gt;

  &lt;li&gt;Unique Per Request &lt;/li&gt;

  &lt;li&gt;Http Context &lt;/li&gt;

  &lt;li&gt;Http Session &lt;/li&gt;

  &lt;li&gt;Hybrid &lt;/li&gt;

  &lt;li&gt;Hybrid Session &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Singleton lifecycle is a mechanism to provide Gang of Four Singleton semantics to an instance. Specifying this lifecycle causes StructureMap to create only a single instance of the concrete type. It holds a reference to this instance and provides it whenever that type is requested. We can specify this lifecycle by using the &lt;em&gt;Singleton&lt;/em&gt; method in the fluent interface thusly:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:ee90433c-04ea-4059-aabc-870ee3236ac2" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;initialise.For&amp;lt;ISingletonService&amp;gt;().Singleton().Use&amp;lt;SingletonService&amp;gt;();&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;If we now add to our example code the following:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:a1445fc4-9cbf-4062-90da-a4096472db89" class="wlWriterEditableSmartContent"&gt;&lt;pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"&gt;&lt;span style="color: #000000;"&gt;var firstSingletonService &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; ObjectFactory.GetInstance&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;ISingletonService&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;();
var secondSingletonService &lt;/span&gt;&lt;span style="color: #000000;"&gt;=&lt;/span&gt;&lt;span style="color: #000000;"&gt; ObjectFactory.GetInstance&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;ISingletonService&lt;/span&gt;&lt;span style="color: #000000;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color: #000000;"&gt;();

Console.WriteLine(&lt;/span&gt;&lt;span style="color: #0000FF;"&gt;string&lt;/span&gt;&lt;span style="color: #000000;"&gt;.Format(&lt;/span&gt;&lt;span style="color: #800000;"&gt;"&lt;/span&gt;&lt;span style="color: #800000;"&gt;Singleton instances are the same: {0}&lt;/span&gt;&lt;span style="color: #800000;"&gt;"&lt;/span&gt;&lt;span style="color: #000000;"&gt;,
    ReferenceEquals(firstSingletonService, secondSingletonService)));
&lt;/span&gt;&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;We get the output:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/WindowsLiveWriter/StructureMapPart2RegistrationOptions_9E19/image_8.png" rel="lightbox"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/WindowsLiveWriter/StructureMapPart2RegistrationOptions_9E19/image_thumb_3.png" width="681" height="396" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p /&gt;

&lt;p /&gt;

&lt;p&gt;The Singleton lifecycle is effective for when global state must be managed or an instance is expensive to create. It is also useful to manage cases where a limited set of resources must be controlled.&lt;/p&gt;

&lt;p&gt;Implementing Singleton manually is generally a bad thing. Manual Singletons result in tight coupling and are difficult to test. The Singleton lifecycle gets around this problem by passing the problem of ensuring that there is only a single instance over to the container. The type marked with the Singleton lifecycle may be implemented as a standard instance type. It may have dependencies to be satisfied as can any other type managed by the container. The only consideration is that the type must be threadsafe when used in multi-threaded environments as the same instance will be provided on all threads.&lt;/p&gt;

&lt;p&gt;Sometimes we wish to manage instances on a per-thread basis rather than globally and for this reason StructureMap provides the Thread Local lifecycle. This lifecycle creates and maintains an instance for each thread that requests the plugin type. Two requests on the same thread will receive the same instance whereas requests on different threads will be given different instances. This is often useful for tracking execution state within a thread or for managing expensive resources that are not threadsafe.&lt;/p&gt;

&lt;p&gt;Using thread local storage in web applications is potentially problematic due to the way ASP.NET handles threads. StructureMap therefore provides lifecycles that use ASP.NET constructs to store data. These are Http Context and Http Session which quite naturally use the ASP.NET Context and Session storage respectively. Using these lifecycles gives instances the lifecycle of the associated ASP.NET storage. You may apply Http Context using the &lt;em&gt;HttpContextScoped&lt;/em&gt; method. For Http Session there is no helper method but you can apply the scope by calling the &lt;em&gt;LifecycleIs&lt;/em&gt; method (for which the &lt;em&gt;Singleton&lt;/em&gt; and &lt;em&gt;HttpContextScoped&lt;/em&gt; methods are convenient wrappers) as shown:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:e4983546-edf3-47f3-9624-2e43f2521c93" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;initialise.For&amp;lt;IHttpSessionService&amp;gt;().LifecycleIs(new HttpSessionLifecycle()).Use&amp;lt;HttpSessionService&amp;gt;();&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;The standard restrictions for using these ASP.NET constructs apply. In particular care should be taken in what is places in the Session.&lt;/p&gt;

&lt;p&gt;In many circumstances code need to be agnostic as to what kind of environment that it runs in. Using Http Context and Http Session ties the code to ASP.NET preventing its use in client or service applications. This scenario is covered by the Hybrid and Hybrid Session lifecycles. These will use the ASP.NET Context or Session (respectively) if it is available. Otherwise they will use thread local storage. Using these lifecycles allows code to run in many environments but instances must adhere to the restrictions of both types of scope. Failure to adhere to the restrictions of both thread local storage and ASP.NET Context (or Session) means that the code will fail in one environment even if it works correctly in the other. The Hybrid lifecycle may be applied using the &lt;em&gt;HybridHttpOrThreadLocalStorage&lt;/em&gt; method. Hybrid Session is applied using the code:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:f8d5c061-3333-4b3b-85da-24caa0d83dda" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;initialise.For&amp;lt;IHybridSessionService&amp;gt;().LifecycleIs(new HybridSessionLifecycle()).Use&amp;lt;HybridSessionService&amp;gt;();&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;Of the built in lifecycles this leaves Unique Per Request. The behaviour of this lifecycle is somewhat more subtle. To illustrate it take this (somewhat contrived) class that requires two instances of ITransientService.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:49b910ce-4549-4664-8e58-bc19de4e29ee" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public interface IRequiresMultipleTransientServices
{
	void MultipleTransientDoStuff();
}

public class RequiresMultipleTransientServices : IRequiresMultipleTransientServices
{
	private readonly ITransientService _firstTransientService;
	private readonly ITransientService _secondTransientService;

	public RequiresMultipleTransientServices(ITransientService firstTransientService,
		ITransientService secondTransientService)
	{
		_firstTransientService = firstTransientService;
		_secondTransientService = secondTransientService;
	}

	public void MultipleTransientDoStuff()
	{
		Console.WriteLine(string.Format("Service instances are the same: {0}",
			ReferenceEquals(_firstTransientService, _secondTransientService)));
	}
}
&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;If we run this we get the output:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/WindowsLiveWriter/StructureMapPart2RegistrationOptions_9E19/image_12.png" rel="lightbox"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/WindowsLiveWriter/StructureMapPart2RegistrationOptions_9E19/image_thumb_5.png" width="681" height="396" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;What we see here is that in the context of a single call to ObjectFactory.GetInstance&amp;lt;T&amp;gt; the container constructs the ITransientService instance only once. Generally this behaviour is desirable or at least neutral. However we may have a case where we need all the instances to be different, for instance if they carry state that could get corrupted if used through different references that are unaware of each other. For this scenario we have the Unique Per Request lifecycle, which can be applied with:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:926c0a05-0571-422b-9342-e90560da9f70" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;initialise.For&amp;lt;IUniquePerRequestService&amp;gt;().LifecycleIs(new UniquePerRequestLifecycle()).Use&amp;lt;UniquePerRequestService&amp;gt;();&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;We can demonstrate the effect with:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:da2f0885-4f75-437d-8293-db2df294b382" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public interface IRequiresMultipleUniquePerRequestServices
{
	void MultipleUniquePerRequestDoStuff();
}

public class RequiresMultipleUniquePerRequestServices : IRequiresMultipleUniquePerRequestServices
{
	private readonly IUniquePerRequestService _firstUniquePerRequestService;
	private readonly IUniquePerRequestService _secondUniquePerRequestService;

	public RequiresMultipleUniquePerRequestServices(IUniquePerRequestService firstUniquePerRequestService,
		IUniquePerRequestService secondUniquePerRequestService)
	{
		_firstUniquePerRequestService = firstUniquePerRequestService;
		_secondUniquePerRequestService = secondUniquePerRequestService;
	}

	public void MultipleUniquePerRequestDoStuff()
	{
		Console.WriteLine(string.Format("Unique per request service instances are the same: {0}",
			ReferenceEquals(_firstUniquePerRequestService, _secondUniquePerRequestService)));
	}
&lt;/pre&gt;&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;&lt;/div&gt;

&lt;p /&gt;

&lt;p&gt;Giving the output:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/WindowsLiveWriter/StructureMapPart2RegistrationOptions_9E19/image_14.png" rel="lightbox"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.abstractcode.com/abstractblog/images/abstractcode_com/abstractblog/WindowsLiveWriter/StructureMapPart2RegistrationOptions_9E19/image_thumb_6.png" width="681" height="396" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;By applying the Unique Per Request Lifecycle we now get a new instance of the dependency everywhere its requested.&lt;/p&gt;

&lt;p&gt;Although a single instance requesting multiple undifferentiated instances of the same dependency is unlikely and generally unhelpful it is not at all unusual that the same dependency will appear multiple times within the same dependency tree for a complex dependency graph. The separate scenario where a type wants multiple distinct concrete dependencies that implement the same plugin type will be discussed later in this series.&lt;/p&gt;

&lt;p /&gt;

&lt;p&gt;Now that we can control the lifecycle of an instance the next post in this series will show how we can control how instances are created.&lt;/p&gt;&lt;img src="http://abstractcode.com/abstractblog/aggbug/206.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Colin David Scott</dc:creator>
            <guid>http://abstractcode.com/abstractblog/archive/2010/06/13/structuremap-part-2-ndash-instance-lifecycles.aspx</guid>
            <pubDate>Sun, 13 Jun 2010 03:22:52 GMT</pubDate>
            <comments>http://abstractcode.com/abstractblog/archive/2010/06/13/structuremap-part-2-ndash-instance-lifecycles.aspx#feedback</comments>
            <wfw:commentRss>http://abstractcode.com/abstractblog/comments/commentRss/206.aspx</wfw:commentRss>
        </item>
    </channel>
</rss>