[pMixins]

A lightweight open source Mixin and AOP framework for C#


Specifying Mixin Constructor

[pMixins] offers the ability to pick which Mixin constructor will be used by setting the ExplicitlyInitializeMixin flag to true.

Setting this flag causes [pMixins] to make the code-behind class implement the CopaceticSoftware.pMixins.Infrastructure.IMixinConstructorRequirement, which has one method InitializeMixin. Inside this method, the Target can create a Mixin and return it to [pMixins].

So given the following Mixin definition:

public class Mixin
{
   public Mixin(string constructorName = "Default")
   {
      ConstructorUsed = constructorName;
   }
   public string ConstructorUsed {
      get;
      private set;
   }
}

Target sets the ExplicitlyInitializeMixin flag and creates a new Mixin in the InitializeMixin method.

Note: The InitializeMixin is implemented explicitly and this is considered best practice. [pMixins] will cast the Target to this interface when calling InitializeMixin and there is no reason for Target to expose this method.

[pMixin(Mixin = typeof(Mixin), ExplicitlyInitializeMixin = true)]
public partial class SpecificMixinConstructor
{
   Mixin IMixinConstructorRequirement<Mixin>.InitializeMixin()
   {
      return new Mixin("Custom");
   }
}

And here is the Test to prove that Target.IntitalizeMixin was called.

[TestFixture]
public class SpecificMixinConstructorTest
{
   [Test]
   public void MixinDefaultConstructorTest()
   {
      //Make sure the Mixin default constructor is correct
      Assert.AreEqual("Default", new Mixin().ConstructorUsed);
   }
   [Test]
   public void TargetUsedCustomConstructor()
   {
      Assert.AreEqual("Custom", new SpecificMixinConstructor().ConstructorUsed);
   }
}

Download the source for this and all other recipes Here!