When writing code we should be able to identify two big group of objects:
- Injectables
- Newables
http://www.loosecouplings.com/2011/01/how-to-write-testable-code-overview.html
http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/
Injectable objects are objects (services) that expose dependencies in their constructors these dependencies are usually resolved using an IoC container, these objects can only ask for other injectables in their constructors
Newable are objects that also expose dependencies in their constructors but newables can only ask for other newable objects (Entities, Value Objects), another characteristic of newable objects is they should not hold a reference to an injectable object
But when writing code, we often need to "inject" a service (injectable) into an Entity (newable)
I have been thinking that maybe exposing a service dependency in a newable object is better doing it at method level but this sounds like a lot of work to do.... just thinking about resolving the dependencies every time a method is called.... well this smells like we would have to use the Service Locator anti-pattern
The way I have solved this is:
Create an interface with a method exposing the dependency (the service will be used in this method)
Create an Extension Method for the interface and place it in a different namespace, perhaps in another assembly, and just wrap the call to the original method resolving the dependency using a service locator
Doing this we have a consistent separation between newable and injectable objects with the ability to use services in our newables easily
- What do you think?
- Using the service locator in an extension method is considered a bad practice?
- How would you unit-test the extension method call?