What is the difference between GlobalContainer and ServiceLocator in Spring for Delphi?

StackOverflow https://stackoverflow.com/questions/14742718

  •  07-03-2022
  •  | 
  •  

They seem so similar. I can register something in the GlobalContainer:

GlobalContainer.RegisterType<TMyImplementation>.Implements<IMyInterface>;

And get an instance via GlobalContainer or ServiceLocator, both of them work:

MyInstance := GlobalContainer.Resolve<IMyInterface>;
MyInstance := ServiceLocator.GetService<IMyInterface>;
有帮助吗?

解决方案

The ServiceLocator is for resolving dependencies in your code when needed. There you don't want to use a reference to the container as that would be totally against the purpose of having losely coupled code.

Personally I agree with those that say that a service locator itself is an anti pattern and should be avoided whenever possible by injecting everything that is possible.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top