Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
        }
like image 713
Mike Avatar asked Dec 30 '25 21:12

Mike


1 Answers

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

like image 72
samy Avatar answered Jan 07 '26 13:01

samy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!