IWindsorContainer container = new WindsorContainer();
//must register typed factory facility otherwise we get errors
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<IFoo>().ImplementedBy<Foo1>().Named("Foo1").LifeStyle.Transient,
Component.For<IFoo>().ImplementedBy<Foo2>().Named("Foo2").LifeStyle.Transient,
Component.For<IFooFactoryWithArgs>().AsFactory(c => c.SelectedWith("MySelector")),
Component.For<ITypedFactoryComponentSelector>().ImplementedBy<SelectorByComponentName>().Named("MySelector")
);
IFooFactoryWithArgs factory = container.Resolve<IFooFactoryWithArgs>();
IFoo foo = factory.GetFoo("Foo3"); //Note, there is no component registered with Foo3 so I would expect NULL to be returned or an error thrown at this point. Unfortunately, Foo1 is returned.
Assert.IsNotNull(foo);
Assert.IsTrue(foo.GetType() == typeof(Foo2));
public class SelectorByComponentName : DefaultTypedFactoryComponentSelector
{
protected override string GetComponentName(MethodInfo method, object[] arguments)
{
bool found = false;
int position = -1;
object componentArgument = null;
string componentName = null;
ParameterInfo[] pInfos = method.GetParameters();
if (pInfos != null)
{
foreach (ParameterInfo pInfo in pInfos)
{
if (pInfo.Name.ToLower() == "componentname")
{
found = true;
position = pInfo.Position;
break;
}
}
}
if (!found)
{
throw new ApplicationException("The current component selctor did not find a 'componentname' argument for the current factory method.");
}
componentArgument = arguments[position];
if (componentArgument == null)
{
throw new ApplicationException("The current component selctor found a null 'componentname' argument for the current factory method.");
}
componentName = componentArgument.ToString(); //no way to validate that we have a valid / registered component name
if (String.IsNullOrEmpty(componentName))
{
throw new ApplicationException("The current component selctor found a null or empty 'componentname' argument for the current factory method.");
}
return componentName;
}
protected override IDictionary GetArguments(MethodInfo method, object[] arguments)
{
var argumentMap = new Arguments();
return argumentMap; //No additional arguments
}
}