An important property of really SOLID code is the fact that constructor calls do not often happen within the actual application code but primarily in the composition root and factory methods where necessary. This makes a lot of sense to me, and I adhere to this wherever I can.
I have created a simple class where it seems to me it is not only allowed, but actually correct to deviate from the above rule. This abstracts some simple Registry queries to facilitate unit testing of some other code:
public class RegistryKeyProxy : IRegistryKey
{
private RegistryKey registrykey;
public RegistryKeyProxy(RegistryKey registrykey)
{
this.registrykey = registrykey;
}
public IRegistryKey OpenSubKey(string subKeyName)
{
var subkey = this.registrykey.OpenSubKey(subKeyName);
return (null == subkey ? null : new RegistryKeyProxy(subkey));
}
public IEnumerable<string> GetSubKeyNames()
{
return this.registrykey.GetSubKeyNames();
}
public object GetValue(string valueName)
{
return this.registrykey.GetValue(valueName);
}
}
The OpenSubKey()
method actually creates an instance of this same class without using a factory, but because of the closed concept that the Registry presents, it actually seems desirable to me not to return anything that looks like a Registry key, but really something that works exactly the same way as the current object.
I know that in the end it's up to me just how SOLID I want to work, but I'd like to know if this generally is a feasible path to go because of the nature of the underlying concept, or if this is not an exception to the rule but actually a SOLID violation.
You are talking about the Dependency Inversion principle. This principle doesn't say that you should never new up objects at all, but it differentiates between two types of objects. Objects that implement behavior (services), and objects that contain data (DTOs, Value Types, Entities).
It would be rather silly in not newing up DTOs, since there is no behavior to be abstracted. They just contain data. (Just as would be silly to add an IPerson
interface to a Person
DTO).
Miško Hevery calls them injectables and newables, which is an nice terminolgoy.
For more information, see this Stackoverflow question: Why not use an IoC container to resolve dependencies for entities/business objects?