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.
[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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With