Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Castle Windsor and how to avoid service locator pattern?

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).

like image 220
Andrew Stephens Avatar asked Oct 21 '22 20:10

Andrew Stephens


1 Answers

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

like image 89
PatrickSteele Avatar answered Oct 28 '22 22:10

PatrickSteele