Skip to content
Sagi edited this page Oct 30, 2015 · 4 revisions

NCop allows to create composites that implement generic types.
Lets create a ICSharpDeveloper that implements a generic IDeveloper<T>.

public interface IDeveloper<T>
{
    string Code();
}

public abstract class CILLanguage
{
    public abstract string Name { get; }
}

public class CSharpLanguage : CILLanguage
{
    public override string Name {
        get {
            return "C# coding";
        }
    }
}

public interface ICSharpDeveloper : IDeveloper<CSharpLanguage>
{
}

Now we can create a mixin that implements IDeveloper<CSharpLanguage> and annotate the ICSharpDeveloper to create the composite.

public class GenericCSharpDeveloperMixin : IDeveloper<CSharpLanguage>
{
    public string Code() {
        return new CSharpLanguage().Name;
    }
}

[TransientComposite]
[Mixins(typeof(GenericCSharpDeveloperMixin))]
public interface ICSharpDeveloper : IDeveloper<CSharpLanguage>
{
}

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) {
        var container = new CompositeContainer();

        container.Configure();
        var person = container.Resolve<ICSharpDeveloper>();
        Console.WriteLine(person.Code());
    }
}

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

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

namespace NCop.Samples
{
    public interface IDeveloper<T>
    {
        string Code();
    }

    public abstract class CILLanguage
    {
        public abstract string Name { get; }
    }

    public class CSharpLanguage : CILLanguage
    {
        public override string Name {
            get {
                return "C# coding";
            }
        }
    }
    
    public class GenericCSharpDeveloperMixin : IDeveloper<CSharpLanguage>
    {
        public string Code() {
            return new CSharpLanguage().Name;
        }
    }

    [TransientComposite]
    [Mixins(typeof(GenericCSharpDeveloperMixin))]
    public interface ICSharpDeveloper : IDeveloper<CSharpLanguage>
    {
    }

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

            container.Configure();
            developer = container.Resolve<ICSharpDeveloper>();
            Console.WriteLine(developer.Code());
        }
    }
}