Windsor lock and how to avoid the service locator pattern?

I use Castle Windsor and in most cases I use DI through class constructors. However, there are times when I find myself using a service locator to resolve an instance of a type that I know is an anti-pattern. I believe that you should also free temporary objects allowed in this way, since Windsor will not do this for you?

An example scenario is a class that mimics a TV remote. The user interface has dozens of buttons, and clicking one at a time leads to the creation of an instance of the class and the execution of a specific object "command". Embedding all of these specific commands through the constructor is clearly impractical, so I would use a service locator, something like this: -

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

How would I reorganize my code to get rid of the service locator and ensure that temporary types are released upon completion (if it is really required by Windsor)?

(I understand that the scenario described above could be solved using the “team” design pattern. It was just an example of a scenario - there are other situations when I use the service locator).

+4
source share
1 answer

I would use a Factory Pattern combination along with a Windsor Typed Factory Object .

+2
source

All Articles