Andrew Stephens
Andrew Stephens

Reputation: 10193

Castle Windsor code design issue

Having used Windsor for quite some time, I'm a little surprised that I haven't come across this "design" issue sooner. I don't know how best to tackle it.

I have a class ConverterService that is used to perform data conversions. This is the interface (I've changed the parameters/return values to objects to simplify the sample):-

public interface IConverterService
{
    object ConvertData(object sourceData);
}

The converter class needs some configuration settings, provided by an ISettingsProvider. The settings are used both in the constructor and the ConvertData() method. I therefore inject the ISettingsProvider into the constructor:-

public class ConverterService : IConverterService
{
    private ISettingsProvider _settingsProvider;

    public ConverterService(ISettingsProvider settingsProvider)
    {
        _settingsProvider = settingsProvider;

        // Do some one-time initialisation using info from settingsProvider
        // and store the results in class variables (not shown), used by ConvertData.
    }

    public object ConvertData(object sourceData)
    {
        // Do the conversion - also uses _settingsProvider,
        // and other variables initialised in the constructor ..
    }
}

Both the ConverterService and SettingsProvider are registered with Windsor in the usual way:-

container.Register(Component.For<IConverterService>().ImplementedBy<ConverterService>().LifeStyle.Singleton);
container.Register(Component.For<ISettingsProvider>().ImplementedBy<SettingsProvider>().LifeStyle.Singleton);

Any class that needs to use the converter gets an IConverterService injected via its constructor - standard stuff. This works fine, but I now need the ability for many different consumers to use the ConverterService with different settings providers (two or three at most).

I can't make ConverterService transient as I don't want the initialisation overhead each time. It feels like I need a separate instance of the ConverterService for each type of ISettingProvider, but I'm not sure if/how I can accomplish this using Windsor, or is a more fundamental refactoring needed?

And how would I register the different settings providers, all of which implement ISettingsProvider? More specifically how would Windsor resolve the correct one (bearing in mind that the ConverterService constructor is merely expecting an ISettingsProvider)?

Any suggestions as to how I should (re-)design the classes would be much appreciated.

Upvotes: 2

Views: 137

Answers (1)

Grofit
Grofit

Reputation: 18445

Can you not use a naming convention for your instances and control them that way? So each instance of your IConverterService would have an associated name to indicate which configuration it was using.

This question features some information on using named components/instances.

Castle Windsor - How to map Named instance in constructor injection

Upvotes: 1

Related Questions