Just assume I have some class Foo, that has two dependencies: an ISerializer<T> and an IFileAccessHandler.
Now this class also has other dependencies, functional dependencies. I don’t want anyone instantiating this class in an invalid state, so I’d also need to pass a domain object in the constructor.
But how can I have that handled by IoC when I also know what domain object to pass in the moment I’m actually creating class Foo?
I made the domain object a property that I have set by a Factory. So the Factory makes a Service Locator call to get a properly instantiated “Foo” class with it’s dependencies, and further fills it up with the correct domain object and returns it.
But is this the best way to go? I would have preferred having the domain object part of my constructor to make it apparant you actually need to work with “Foo”.
Any ideas?
Am I missing something here?
The default solution to DI when you can’t wire up a concrete type at registration time is to use an Abstract Factory
In your case, I would define an IFooFactory interface:
This will allow you to define a concrete implementation that knows about your infrastructure services.
In this way you can protect the invariants of your Foo class, enabling you to stay with Constructor Injection.
In the DI container, you can register the IFooFactory and corresponding implementation. Everywhere you have a DomainClass instance and need a Foo instance, you would then take a dependency on IFooFactory and use that.