3 ms·
Nah, ServiceLocator is another overly abstruse pattern. What you do instead is just: public static IMyService myService; public static IMyService getMyServic
by didibus 6y ago
Nah, ServiceLocator is another overly abstruse pattern.
What you do instead is just:
public static IMyService myService;
public static IMyService getMyService()
{
if myService
return myService;
else if(isInTest())
return mockedMyService;
else
return new MyProdService(wtv);
}
And call that in your controller that needs to use MyService.
- sharpercoder 6y agoAbove code is the servicelocator pattern. It's just for one service.
- deleted 6y ago[deleted]
- didibus 6y agoServiceLocator has you create a runtime service registry where you can dynamically register and fetch instances too and from. And often that means it bypasses static type checking, as you might be adding and fetching services by name using a string. This is different in that it's static. You don't add a service to it, it creates it the first time you ask for it (if singleton), or everytime you ask for it (otherwise), or pools it, etc. I recon some similarities, but most enterprise "service locator" involve a lot more than this, and often are meant to give you this runtime dynamism where you can load and unload services as the app is running, etc. making them way more complex for apps that don't care about this.
- shireboy 6y agoActually, as written, myService never gets set, but I think I know what you mean. This is not thread-safe and assumes you want singleton. To use it you would in each controller do: var service = Startup.getMyService(); And potentially know if the controller should dispose service. This doesn't seem much less "in the way" or "massive" than: services.AddSingleton<IMyService,MyService>();