Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Using StructureMap

Acoustic edited this page Sep 14, 2010 · 6 revisions

Configuring Snap with StructureMap

Dependency Version
Snap Current
Snap.StructureMap.dll Current
StructureMap.dll v2.6.1

Configuration

StructureMap uses the ObjectFactory class as the primary entry point for type creation. As a static class, StructureMap’s ObjectFactory requires no instance construction. This makes configuration particularly simple using Snap’s configuration syntax.

//Configure Snap to use StructureMap using the generic For method
SnapConfiguration.For<StructureMapAspectContainer>(c =>
{
    // Tell Snap to intercept types containing "Snap.Tests" in their namespace.
    c.IncludeNamespaceRoot("My.Namespace");
    //c.IncludeNamespace("My.Namespace*");
    // Register your custom interceptor (a.k.a. an aspect).
    c.RegisterInterceptor<HandleErrorInterceptor>(); 
    // Register another interceptor
    c.RegisterInterceptor<LogStuffInterceptor>(); 
});
// Register your own types with StructureMap.  Alternatively, you 
// can use a StructureMap Registry.
ObjectFactory.Configure(c => c.For<IMyType>().Use<MyType>());
// Get an AoP wrapped instance of your type from StructureMap
var badCode = ObjectFactory.GetInstance<IMyType>();

The configuration step only needs to be run once, ideally at application start up. For method interception to function properly, configuration needs to be run prior to accessing types from your IoC container (as in the example above).

The next step is to create an interceptor. Take a look at the following example of a sample HandleErrorInterceptor

public class HandleErrorInterceptor : MethodInterceptor
{
    public override void InterceptMethod(IInvocation invocation, MethodBase method, Attribute attribute)
    {
        try
        {
            // Attempt the method call
            invocation.Proceed();
        }
        catch
        {
            // Do something useful here.
        }
    }
}

Finally, this interceptor looks for a particular attribute to determine which methods to intercept. This example uses a HandleErrorAttribute:

public class HandleErrorAttribute : MethodInterceptAttribute
{ }

Happy coding!