Search code examples
c#castle-windsor

Supplying different configurations of the same type to different implementations?


I have two implementations that each require a different set of configuration data of the same type:

public ConsumerA(Configuration config) : IConsumerA { ... }
public ConsumerB(Configuration config) : IConsumerB { ... }

In my installer, I have Windsor resolving the implementations:

container.Register(
    Component.For<IConsumerA>().ImplementedBy<ConsumerA>().LifestyleTransient(),
    Component.For<IConsumerB>().ImplementedBy<ConsumerB>().LifestyleTransient()
);

How can I ask Windsor to resolve the configurations based on the respective implementations?


Solution

  • What I ended up doing was naming the configurations and using a factory, sort of like so:

    Component.For<IConsumerA>().ImplementedBy<ConsumerA>()
        .DependsOn(Dependency.OnComponent(typeof(Configuration), "configurationA")).LifestyleTransient(),
    Component.For<IConsumerB>().ImplementedBy<ConsumerB>()
        .DependsOn(Dependency.OnComponent(typeof(Configuration), "configurationB")).LifestyleTransient(),
    
    Component.For<Configuration>().UsingFactoryMethod(
       k => k.Resolve<ConfigurationFetcher>()
           .GetConfigurationSection<ConfigurationSection>(ConfigurationSection.ConfigurationASectionName)
           .GetConfiguration()).Named("configurationA"),
    Component.For<Configuration>().UsingFactoryMethod(
       k => k.Resolve<ConfigurationFetcher>()
           .GetConfigurationSection<ConfigurationSection>(ConfigurationSection.ConfigurationBSectionName)
           .GetConfiguration()).Named("configurationB"),