5
votes

I'm using Castle Windsor, and in most cases I'm using DI via class constructors. However there are times where I find myself using a service locator to resolve an instance of a type, which I know is an anti-pattern. I believe you must also release transient objects resolved in this manner, as Windsor won't do this for you?

An example scenario would be a class that simulates a TV remote. The UI has dozens of buttons, and clicking one results in the class instantiating and executing a particular "command" object. Injecting all these concrete commands via the constructor clearly isn't feasible, so I would use a service locator, something like this:-

private void PowerButtonOnClick()
{
    var command = ServiceLocator.Current.Resolve<IPowerOnCommand>();
    command.Execute();
}

How would I refactor my code to get rid of the service locator, and ensuring that transient types are released when finished with (if this is indeed required by Windsor)?

(I realise the above scenario could be solved using a "command" design pattern. It was just an example scenario - there are other situations where I'm using a service locator).

1

1 Answers

3
votes

I would use a combination of the Factory Pattern along with Windsor's Typed Factory Facility.