SheepAOP Part 4: Integrating with IoC containers

This Series

  1. Getting Started with SheepAOP
  2. Pointcuts and SAQL Basics
  3. Aspects Lifecycles & Instantiations
  4. Integrating with IoC containers
  5. Aspects Inheritance & Polymorphism
  6. Attributive Aspects (ala PostSharp)
  7. Unit-testing your aspects
  8. Extending SheepAop

Aspect Factory

In the previous post, we have discussed at great length about various SheepAop lifecycles and how they affect the specific points at which SheepAop should instantiate new aspect objects. Whenever your lifecycle strategy determines that a new aspect needs to be created, by default SheepAop will look for a default parameterless constructor in your aspect class.

SheepAop lets you to can change this behavior and use your own IoC container to manage the instantiations of your aspects and wire up their dependencies. This is done by implementing your own custom AspectFactory. For example, the following code will hook SheepAop with StructureMap.

public class StructureMapAspectFactory: AspectFactory
{
   private readonly Container _container;
   public StructureMapAspectFactory(Container container)
   {
      _container = container;
   }

   public override object CreateInstance(Type type)
   {
      return _container.GetInstance(type);
}
}

And you add the following code to the entry point of your program (i.e. Global.asax in a web application)

AspectFactory.Current = new StructureMapAspectFactory(container);

All pretty straightforward. Now if you take the example aspect class from few posts back…

[Aspect]
public class PurchasingNotificationAspect
{
   private readonly INotificationService _notifier;
   public PurchasingNotificationAspect(INotificationService notifier)
   {
      _notifier = notifier;
   }

   [SelectPropertySets("Name:'StockQty' & InType:Name:'Product'")]
   public static void SettingProduct(){}

   [Around("SettingProduct")]
   public void CheckStockForNotification(PropertySetJoinPoint jp)
   {
      jp.Proceed();
      if ((int)jp.Value < 5)
      {
         _notifier.Send(Notice.Restock, (Product)jp.This);
      }
   }
}

… StructureMap will now handle the instantiations of this aspect class, including the wiring of the INotificationService dependency via the constructor.

I highly recommend to always register all your aspect classes using transient configuration on your IoC container, and to leave it to SheepAop to handle the lifecycle management of the instances.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s