Avoiding Service Locator Antipattern with legacy app not designed for IOC

Viewed 1449

I have read often that Service Locators in IOC are an anti-pattern.

Last year we introduced IOC (Ninject specifically) to our application at work. The app is legacy, it's very big and it's fragmented. There are lots of ways a class, or a chain of classes can get created. Some are created by the web framework (which is custom), some are created by nHibernate. Lots are just scattered around in weird places.

How would we handle the different scenarios and not come up with something thats not at least ServiceLocatorish and not end up with different kernels in different places (scopes like singleton, HttpRequest and thread are important).

Edit I'll add a little more detail to what led us to our current SL pattern.

We actually don't want multiple kernels. We just want one (and indeed because of the SL we only have the one static one). Here is our setup:

1) We have Ninject Modules in 7-8 different projects/assemblies. When our app (a webapp) starts the modules are gathered via assembly scanning and loaded into a kernel and placed in the Service Locator. So all that is rather expensive.

2) We have a custom UI framework that's construction happy. Think of around 120 tabbed forms which each construct 1-10 tab pages as part of their lifecycle. The SL is strategically used in 5-6 places which cover all of this either as pure resolution or doing post instantiation injection of properties only.

3) Anything under the UI is not covered by those top level calls and if those classes want to use IOC they need to come up with their own strategy. There are various different little frameworks which are each their own little worlds.

So the ideal way of doing it from what I have read is injecting a kernel whenever you need to access IOC...well that's all fine and good; we do keep the use of the SL to a minimum.

But where am I getting this kernel from? I don't want to construct and register up a new one everywhere. It seems like I would have to get it out of static context or factory so I can ensure that the kernel I'm using is holding on to the same scoped objects that everyone else is using and also to avoid the expense of registering all of the modules. At that point, whatever that thing is seems a lot like a Service Locator right?

Keep in mind also that this app is HUGE and tightly coupled. We don't have the luxury of spending a few months in one go of refactoring it. The SL seemed like a good way for us to slowly work IOC in where we could as we had time.

1 Answers
Related