Reputation: 8348
I'm a little confused about the differences of the SOLID dependency Inversion principle and IOC containers. Should there only be one class responsible for wiring all the dependencies? I don't want to use a blackbox IOC container and wire these things up myself. I don't want to get distracted in the beginning with making a super generic one of my own. Hardwiring in just one place or class would do just great. Nor do I want to use any @Inject or @Autowired etc. That just hides the juicy details..
I want to understand how I would wire dependencies in one single place (a class or some properties file) and have the rest of the system not hardwired to specific implementations. I'm approaching it this to better understand how dependency inversion works and how its related to dependency injection.
So with that being said, how would I wire an EmployeeDAO interface for saving and deleting employees in a database or a filesystem or a nosql datastore? I'll be grateful for any examples for this usecase.
Thanks in advance.
Upvotes: 0
Views: 222
Reputation: 28036
I would recommend that you don't try to roll your own container. Either use a container off the shelf, or don't use a container at all (it sounds like you want the latter).
public interface IEmployeeDAO
{
void SaveEmployee(Employee employee);
}
public class ClassThatNeedsToSaveEmployees
{
private readonly IEmployeeDAO _employeeDAO;
public ClassThatNeedsToSaveEmployees(IEmployeeDAO employeeDAO)
{
_employeeDAO = employeeDAO;
}
}
Now to instantiate the class, you need do something like this:
var myClass = new ClassThatNeedsToSaveEmployees(new EmployeeDAO());
Although it gets hairier as your dependencies have dependencies, e.g.:
var myClass = new ClassThatNeedsToSaveEmployees(new EmployeeDAO(new DatabaseConnectionFactory(new ConfigurationFileReader())));
In simple applications, this may not be a problem, but as your dependency graph grows, this becomes more difficult to maintain. A container adds a bit of complexity to the setup of your application (and a bit of a learning curve), but it eases the pain of adding dependencies to your classes by having them automatically get injected, provided they are registered correctly. So if your DatabaseConnectionFactory implementation needed an additional dependency of IWidget, you would just add an IWidget parameter to the constructor and it would automatically get injected.
Upvotes: 3