I have 2 components (AWriter and BWriter) where both implement IWriter interface. And I have 2 components (AComponent and BComponent) where both implement interface IComponent and both have dependency on IWriter. But in AComponent I want to tell Windsor to give me instance of AWriter, and in BComponent I want to tell Windsor to give me instance of BWriter. How to do that?
Here is the code:
public interface IWriter
{
void Write();
}
public class AWriter : IWriter
{
public void Write()
{
Console.Write("A writer");
}
}
public class BWriter : IWriter
{
public void Write()
{
Console.Write("B writer");
}
}
public interface IComponent
{
void Do();
}
public class AComponent : IComponent
{
IWriter writer;
public AComponent(IWriter writer)
{
this.writer = writer;
}
public void Do()
{
writer.Write();
}
}
public class BComponent : IComponent
{
IWriter writer;
public BComponent(IWriter writer)
{
this.writer = writer;
}
public void Do()
{
writer.Write();
}
}
NOTE: This is just simplified problem and putting AWriter in AComponent and BWriter in BComponent as dependency is not an option. Also AComponent and BComponent might look same at this example, but this is not real situation. I have much more dependencies and components in real situation and I didn’t wanted to bother with that.
So, is there a way to somehow specify by some attribute which implementation should Castle give me?
You want to be using named components and service overrides. See here in Windsor’s documentation for help: http://docs.castleproject.org/Windsor.Registering-components-one-by-one.ashx
Using fluent registration you’d do something like:
Then:
Of course this will result in two registrations for IComponent, but again if you need to inject the specific instances you can name them and use service overrides to inject each implementation into its appropriate spot in your dependency structure.