Saturday, December 1, 2012

Use of Castle.Windsor typed factory component selector

Some times you need to create objects on the fly and you want their dependencies be resolved by DI container.
Using Windsor Typed Factory Facility gives you ability to avoid using service locator. This technique described pretty well in documentation and I am not going to repeat it here. What I am going to talk is how to use typed factory component selector.
Lets look on the following model

We have here some sort of D&D game. Sword, Short Sword and Knife implements IWeapon. And Warrior and Thief implements ICharacter.
I want to have ICharacterFactory with CreateCharachter method that receive string argument specifying what class of a character I want to create.

so that I can use in code:

To do this I will override DefaultTypedFactoryComponentSelector and provide it during registration of my ICharacterFactory

Now, when thief character will be created he will hold short sword in his right hand and knife in the left. When we create warrior it have only one sword.