Allowing Castle Windsor to resolve two interfaces to the same instance

There are times when it’s useful to be able to resolve two different interfaces to the same type when using Castle Windsor for dependency injection. Given a class called MyClass which implements two interfaces, IOne and ITwo, the following code will achieve this:

container.Register(
                Component.For<IOne, ITwo>()
                .ImplementedBy(typeof(MyClass))
                .LifeStyle.Singleton);

This can be simply demonstrated using the following classes:

namespace TwoInterfaces
{
    public interface IOne
    {
        string GetMessage();
    }

    public interface ITwo
    {
        string GetMessage();
    }

    public class MyClass : IOne, ITwo
    {
        public string GetMessage()
        {
            return "Hello World!";
        }
    }
}

…in a console application. Running the following program class:

using System;

namespace TwoInterfaces
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var injector = Injector.Instance;

            var one = injector.Resolve<IOne>();
            var two = injector.Resolve<ITwo>();

            Console.WriteLine(one.GetMessage());
            Console.WriteLine(two.GetMessage());
            Console.WriteLine(one.Equals(two));

            Console.WriteLine("Press RETURN to exit...");
            Console.ReadLine();
        }
    }
}

…yields:

CastleWindsorTwoInterfaces

…as expected. My post entitled Basic dependency injection with Castle Windsor explains how to set up a fully working Castle Windsor injector in more detail.

Leave a Reply

Your email address will not be published. Required fields are marked *