Let’s imagine that we want a particular interface resolved with a particular element (another class for example, or the same class but with a different lifestyle) just when is a dependency of a particular object. In all other situations we want to use another basic rule. How can we do this with Castle.Windsor?
First of all we define the two different rules (in this case we want our interface to be resolved with an Entity Framework context with two different lifestyles)
//This is the default rule. In Castle.Windsor, when multiple rules match, the first one wins. //If we aren't sure about the rule's order (because the rules are in different files) we can //use the IsDefault() method to force Castle.Windsor to use a particular rule as default Component.For<MyDependency>().ImplementedBy<MyDependency>().LifestylePerWebRequest().IsDefault(), //This is our alternative rule. In order to use it we must provide a name with the Named() method, //so we can specifically instruct Castle.Windsor to use this rule when resolving a dependancy Component.For<MyDependency>().ImplementedBy<MyDependency>().Named("MyDependency_Singleton"),
(Notice that in this case we are defining a rule for a dependency that isn’t an interface, but a normal class, so we are telling Castle.Windsor to use the same class to resolve the dependency.) As we can see our two rules are different just for the lifestyle: the first one is for web request and the second one is a singleton (as default). We know that the first rule is the default one, so we are sure that the second rule will never be used, unless we expressly require to use it. Ho can we do this? Within the configuration of the object which have a dependency on MyDependency and that must resolve that dependency using the second rule we can write:
Component.For<IMyRepository>().ImplementedBy<MyRepository>() .DependsOn(Dependency.OnComponent("myDependencyParameterName", "MyDependency_Singleton"),
Here we are using the DependsOn() method (the same we use to specify a constant dependency) to say that we want to to resolve the “myDependencyParameterName” contructor’s parameter using the “MyDependency_Singleton” rule, instead of the default one.