Skip to content

Building Your First Composite

Sagi edited this page Apr 3, 2015 · 31 revisions

Composites are the artifacts of NCop processing, and composed from Mixins and Aspects.

The smallest composite type is called Atom Composite.
The first thing that we have to do is define an interface.

public interface IDeveloper
{
    void Code();
}

In order for NCop to identify this type as a composite we should annotate the type with TransientCompositeAttribute attribute.

using NCop.Composite.Framework;

[TransientComposite]
public interface IDeveloper
{
    void Code();
}

Now IDeveloper can be detected as a composite but it does not have an implementation.
Let's create a new type that will implement IDeveloper.

public class CSharpDeveloperMixin : IDeveloper
{
    public void Code() {
        Console.WriteLine("C# coding");
    }
}

In order for NCop to apply the implementation of CSharpDeveloperMixin to IDeveloper, we need to introduce a Mixin.
We do that by annotating the composite with a MixinsAttribute attribute that has a specification of CSharpDeveloperMixin as the implementation type.

using NCop.Mixins.Framework;
using NCop.Composite.Framework;

[TransientComposite]
[Mixins(typeof(CSharpDeveloperMixin))]
public interface IDeveloper
{
    void Code();
}

That's all, we've finished creating the composite type.
Now we need to create a CompositeContainer which will handle two things:

  1. Craft the real implementation in runtime.
  2. Act as a Dependency Injection Container that will resolve our type.
using System;
using NCop.Mixins.Framework;
using NCop.Composite.Framework;

class Program
{
    static void Main(string[] args) {
        IDeveloper developer = null;
        var container = new CompositeContainer();

        container.Configure();
        developer = container.Resolve<IDeveloper>();
        developer.Code();
    }
}

The expected output should be "C# coding".
Your end result of the code should be similar to this:

using System;
using NCop.Mixins.Framework;
using NCop.Composite.Framework;

namespace NCop.Samples
{   
    [TransientComposite]
    [Mixins(typeof(CSharpDeveloperMixin))]
    public interface IDeveloper
    {
        void Code();
    }

    public class CSharpDeveloperMixin : IDeveloper
    {
        public void Code() {
            Console.WriteLine("C#");
        }
    }

    class Program
    {
        static void Main(string[] args) {
            IDeveloper developer = null;
            var container = new CompositeContainer();

            container.Configure();
            developer = container.Resolve<IDeveloper>();
            developer.Code();
        }
    }
}

Atom Composite - The smallest composite type which acts as the mixin interface and the composite type altogether.