[pMixins]

A lightweight open source Mixin and AOP framework for C#


Avoid implementation inheritance whenever possible

James Gosling Father of Java

Welcome to [pMixins]

[pMixins] is a simple and straight forward framework for easy mixin and AOP in C#. In essence, it is a Visual Studio Plugin that generates code-behind files; auto-generating the boilerplate and weaving code to compose the mixins into the target. This is the same mechanism asp.net uses to convert markup into .net code.

So let's see a hello world example. I have a class, aptly named HelloWorld. It has a method, SayHello:

public class HelloWorld
{
   public string SayHello()
   {
      Console.WriteLine("Saying Hello");
      return "Hello World!";
   }
}

I want the SayHello method to be available from my class Introduction. I mark my class partial, so that [pMixins] can work with it, and then decorate the class with the pMixin attribute.

[pMixin(Mixin = typeof(HelloWorld))]
public partial class Introduction
{
}

And that's it. Introduction now has a method called SayHello!

class Program
{
   static void Main(string[] args)
   {
      Console.WriteLine(new Introduction().SayHello());
   }
}
     Saying Hello
     Hello World!

Aspect Oriented Programming

Continuing from the example above, [pMixins] can intercept calls to mixed in members. By implementing IMixinInterceptor (or extending the convenience class MixinInterceptorBase) you can create Aspects:

public class Aspect : MixinInterceptorBase
{
   public override void OnBeforeMethodInvocation(object sender, MethodEventArgs eventArgs)
   {
      Console.WriteLine("Before " + eventArgs.MemberName);
   }
   public override void OnAfterMethodInvocation(object sender, MethodEventArgs eventArgs)
   {
      Console.WriteLine("After " + eventArgs.MemberName);
      eventArgs.ReturnValue = eventArgs.ReturnValue + " - Now with Aspects!";
   }
}

The Aspect class will write the name of a method before and after the method is called and prepends the string - Now with Aspects! to the end of the return value.

Wiring in the Aspect class is again done using the pMixin attribute:

[pMixin(Mixin = typeof(HelloWorld), Interceptors = new[] {
   typeof(Aspect)
})]
public partial class AspectIntroduction
{
}

And with no changes to the Program:

class Program
{
   static void Main(string[] args)
   {
      Console.WriteLine(new AspectIntroduction().SayHello());
   }
}

This is the result:

     Before SayHello
     Saying Hello
     After SayHello
     Hello World! - Now with Aspects!