Search code examples
c#.netunity-containercastle-windsor

What is the equivalent for this in Castle Windsor?


Supposing I have e.g.:

public interface IYetAnotherInterface : IMyBaseInterface
public class JustAClass: IYetAnotherInterface

using Unity DI container this is valid:

container.RegisterType<IMyBaseInterface, IYetAnotherInterface>();
container.RegisterType<IYetAnotherInterface, JustAClass>();

How can I do this using Castle Windsor? This fails:

container.Register(
   Component
      .For<IMyBaseInterface>()
      .ImplementedBy<IYetAnotherInterface >());

container.Register(
   Component
      .For<IYetAnotherInterface >()
      .ImplementedBy<JustAClass>());

I am trying to resolve the IYetAnotherInterface in a ctor, e.g.

public Foo(IYetAnotherInterface i, ...)

Solution

  • I'm not sure what the container.RegisterType<Interface1, Interface2>(); thing does in Unity. It looks like it hooks up the component for one to also resolve for the other?

    If that's the case, you have two options.

    • Go with what @vzwick's answer says if you want to have two components.

    • Go with the following if you want just one component.

    .

    Component
       .For<IMyBaseInterface, IYetAnotherInterface>()
       .ImplementedBy<JustAClass>()
    

    So in the first option you end up with two separate components, both backed by JustAClass, each exposing a single service interface: one for IMyBaseInterface and the other for IYetAnotherInterface.

    In the second option you end up with a single component, exposing both IMyBaseInterface and IYetAnotherInterface.

    The documentation has a pretty good explanation of the concepts, and I highly recommend familiarising yourself with it.