Here is the example:
interface IComponentA {};
class ComponentA : IComponentA { };
interface IComponentB { };
class ComponentB : IComponentB { };
interface IComponentC { };
class ComponentC : IComponentC
{
public ComponentC(IComponentA a)
{
Console.WriteLine("Constructor A");
}
public ComponentC(IComponentB b)
{
Console.WriteLine("Constructor B");
}
};
All these components are registered in Castle Windsor container.
But class ComponentC
has 2 overloaded constructors. Any of them can be used when ComponentC
is being activated.
I need ComponentC(IComponentB b)
constructor to be used.
For a moment I'm using UsingFactoryMethod() method to resolve that:
container
.Register(Component
.For<IComponentA>()
.ImplementedBy<ComponentA>())
.Register(Component
.For<IComponentB>()
.ImplementedBy<ComponentB>())
.Register(Component
.For<IComponentC>()
.UsingFactoryMethod(() => new ComponentC(
container.Resolve<IComponentB>())));
It works, but probably Castle Windsor provides some better way to do that?
Any help is really appreciated.
Thanks.
Windsor doesn't provide support for this scenario, because it breaks one of the unwritten assumptions it (and most containers) operates based on: "all constructors are created equal".
What that means, is that regardless of which constructor it choses there should be no functional differences in the behaviour of the component. All things being equal the more dependencies a component has the more capabilities it has, that's why Windsor will tend to pick greedier constructors first, but in case like yours I'd say either of two things are happening:
Another scenario I've seen is something like that:
public class Foo
{
public Foo(ISession session){/*code*/}
public Foo(ISessionFactory factory):this(factory.OpenSession()){}
}
While this might seem like a clever idea at first, at best it's superfluous, confusing and unnecessary. If your case looks like this one, I'd just remove the second constructor.