Can castles windsor container return the same instance of a component implementing 2 interfaces
Asked Answered
P

2

5

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.

Penelopepeneplain answered 17/8, 2009 at 11:37 Comment(1)
Question added to the Windsor FAQ: using.castleproject.org/display/IoC/FAQGrimace
G
11
[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);
    }
}
Grimace answered 17/8, 2009 at 14:2 Comment(2)
Oh son of a b... really? You can do that? Lord knows the workarounds I've come up with.Annorah
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?Penelopepeneplain
S
1

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.

Swallowtailed answered 17/8, 2009 at 12:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.