Using StructureMap - TylerBrinks/Snap GitHub Wiki
Dependency | Version |
Snap | Current |
Snap.StructureMap.dll | Current |
StructureMap.dll | v2.6.1 |
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!