Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 302
Gareth Avatar asked Aug 17 '09 11:08

Gareth


2 Answers

[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);
    }
}
like image 113
Mauricio Scheffer Avatar answered Oct 23 '22 08:10

Mauricio Scheffer


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.

like image 23
mookid8000 Avatar answered Oct 23 '22 08:10

mookid8000