This project is read-only.

Using Mixins with Unity

"Mixins are a powerful concept for object-oriented class composition." This is a quote from the top of the homepage of the re-mix Framework.

This page provides a lot of additional information about what mixins are and how they can be used to make your life as developer easier. They also provide a word of warning not to over-use them.

Anyway. re-mix requires you to create objects that you want to enhance with mixins via an object factory. If you are using Unity in your application the chances are high that you don't want to introduce a second way to instantiate your business objects. But fear not! There is a convenient way to enable Unity to use re-mix' factory under the covers.

Say you have a domain object that performs some immensely complex task and returns the tasks output via its ToString() method.

public class ComplicatedBusinessObject
  public ComplicatedBusinessObject(ILogger logger) { }
  public override string ToString()
    return "1";

To demonstrate that Unity will resolve that class's dependencies the constructor also takes an ILogger as parameter.

Now you can configure re-mix to override that special part of your business logic (namely the ToString() method).

var builder = MixinConfiguration.BuildNew();
var config = builder.BuildConfiguration();

It will use a prepared class called ToStringMixin. Beside the OverrideTargetAttribute this is a POCO with no special dependencies or prescribed ancestors.

public class ToStringMixin
  public new string ToString()
    return "2";

Now you have to tell Unity to use re-mix' object factory to do its magic.

var container = new UnityContainer();
container.RegisterType<ILogger, Logger>();

Add the MixinExtension. Tell Unity how to resolve ILogger. Done.

The following snippet is an extract from a unit test that can be found in the TecX.Unity.Mixin.Test project.

using (config.EnterScope())
  var target = container.Resolve<ComplicatedBusinessObject>();
  Assert.AreEqual("2", target.ToString());

The source code for the MixinExtension can be found in the TecX.Unity.Mixin project.

Last edited Dec 16, 2011 at 9:40 AM by weberse, version 1


No comments yet.