views:

421

answers:

2

Is is possible with the Castle Windsor Container to have one component implement two different interfaces and then when resolving it to return the same component instance? For example;

var windsor = new WindsorContainer()
    .AddComponent<InterfaceA, ClassAB>()
    .AddComponent<InterfaceB, ClassAB>();

var classAB1 = windsor.Resolve<InterfaceA>();
var classAB2 = windsor.Resolve<InterfaceB>();

Assert.AreSame(classAB1, classAB2);

If I try this as shown I get an exception with the message There is a component already registered for the given key, if I provide different keys then it returns two separate instances of the class ClassAB.

Edit: Ideally I would like to do this in a config file.

A: 

I know one solution to this - it can be done like so:

var someInstance = new Instance();
var container = new WindsorContainer();

container.Register(Component.For(typeof(IFirstInterface)).Instance(someInstance));
container.Register(Component.For(typeof(ISecondInterface)).Instance(someInstance));

... but then you lose the container's ability to instantiate the Instance class, so its dependencies will not be automagically resolved. Of course, if your instance does not have any dependencies, you probably don't care about this.

mookid8000
+2  A: 
[TestFixture]
public class Forwarding {
    public interface InterfaceA {}

    public interface InterfaceB {}

    public class ClassAB: InterfaceA, InterfaceB {}

    [Test]
    public void tt() {
        var container = new WindsorContainer();
        container.Register(Component.For<InterfaceA, InterfaceB>().ImplementedBy<ClassAB>());
        var a = container.Resolve<InterfaceA>();
        var b = container.Resolve<InterfaceB>();
        Assert.AreSame(a, b);
    }
}
Mauricio Scheffer
Oh son of a b... really? You can do that? Lord knows the workarounds I've come up with.
George Mauer
Thanks for the replies, this looks great but just to move the goal posts do you know if this is also possible to do in a config file?
Gareth
Yes, it's possible. See http://stackoverflow.com/questions/274220
Mauricio Scheffer
Fantastic, thank you
Gareth

related questions