Search code examples
castle-windsorioc-containercastle

Register Components Based on appsetting value?


Does Castle windsor offer a cleaner or recommended way of performing registration based on an appsettings value in the app.config/web.config? Example of what i am doing now is below

        if (ConfigurationManager.AppSettings["UseFakeEmailService"] == "true")
        {
            container.Register(Component.For<IEmailService>().ImplementedBy<EmailService>().IsFallback().LifestyleTransient());
            container.Register(Component.For<IEmailLogger>().ImplementedBy<EmailLogger>().LifestylePerThread());
        }
        else
        {
            container.Register(Component.For<IEmailService>().ImplementedBy<FakeEmailService>().IsFallback().LifestyleTransient());
            container.Register(Component.For<IEmailLogger>().ImplementedBy<FakeEmailLogger>().IsFallback().LifestyleTransient());
        }

Solution

  • There are multiple ways to clean this kind of writing up. The first coming to mind would be to declare a factory method as the way to create your component:

    Component.For<IEmailService>().UsingFactoryMethod(() => (configValue ? new EmailService() as IEmailService: new DummyEmailService() as IEmailService))
    

    If you really want to get fancy, or if you have many classes that follow this pattern, you could have a look at custom resolvers that can help you determine what to return at runtime.

    There is also the IsDefault filter mechanism that can help you determine what component to resolve by default:

    container.Register(
        Component.For<IDummy>().ImplementedBy<TestDummy>().IsDefault(t => isTestMode == true)
        );
    

    But if you want to register only the types that are relevant to your mode, then you are doing the right thing. You can perhaps push the installation in a IWindsorInstaller to isolate it but I know of no other mechanism to handle it.

    EDIT: and I should have looked harder, there are conditional registration mechanisms