Search code examples
c#castle-windsor

How to add dependency to existing Castle Windsor registration?


We have a bunch of controllers we register with Castle via a BasedOn query. One of these controllers we would like to add an extra configuration dependency on. It is possible that we could register that parameter with all controllers. The following code is how we worked around the problem, but I would like to know if there is a more elegant/built in solution.

public class ControllersInstaller : IWindsorInstaller
{
    private readonly IAppConfig _appConfig = new AppConfig();
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(FindControllers().Configure(ConfigureComponentRegistration).LifestyleTransient());

        container.Register(Component.For<BarController>()
            .LifestyleTransient()
            .DependsOn(Dependency.OnValue("faxNumber", 
            _appConfig.GetAppSetting<string>("FaxNumber"))));
    }

    private void ConfigureComponentRegistration(ComponentRegistration obj)
    {
        obj.LifestyleTransient();
    }

    private BasedOnDescriptor FindControllers()
    {
        return Classes.FromThisAssembly()
            .BasedOn<IController>()
            .If(Component.IsInSameNamespaceAs<FooController>(true))
            .If(t => t.Name.EndsWith("Controller") && t.Name != "BarController")                
            .LifestyleTransient();
    }
}

Solution

  • I would suggest that you simply override the existing registration with a more specific version, that has necessary dependency from _appConfig. Therefor, you don't have to use this filter:

    t.Name != "BarController"
    

    Check out my answer here, for how to override existing components: https://stackoverflow.com/a/37832194/644891