Dependency Injection And The Domain
I've always been slightly against using DI to inject repositories into the domain on the code base I work on, because I think it increases complexity and obviously you are then coupled to the DI framework. In thus use a custom approach based on Fowlers' Registry Pattern.
Having said that there is an interesting discussion of the topic in an excellent blog entry by one of the contributors to the DDD forum, and the auto mocking container approach would make using DI and integrating it into testing easier.
I still think the registry based approach was the correct one for us, its not particularly new or fancy but it works well.
Having said that I guess it is worth considering Windsor, or something like Microsofts DI approach, as an alternative...though I still prefer that my domain and its unit tests have no association with something like Windsor as I want to make the domain and its tests as simple as possible.
Hi Colin,
ReplyDeleteI agree that it is advisable to keep the domain layer as free from external libraries as much as possible (how else would we strive for the mecca that is POCO / POJO). However to circumvent your concern with your domain knowing about Windsor it would be easy enough to create a proxy onto your chosen IoC. Therefore you domain knows about the proxy interface, but not the library which is serving it up.
Definitely, but then we've introduced IoC and an associated abstraction layer and the complexity shouldn't be ignored.
ReplyDeleteTo be fair Fowler covers this sort of stuff very well in his article, and I tend to think he is right that a simple approach shouldn't be ruled out:
http://www.martinfowler.com/articles/injection.html
Agreed that you should keep it as simple as possible!
ReplyDeleteHowever, you suggest that you are happy to use a Registry / Service Locator pattern, do you allow references to this from your domain? If so surely is cleaner to inject dependancies into your domain (or indeed the container itself), rather than the domain layer locating these itself?
Always a tradeoff, I'll defer to Fowler here though:
ReplyDelete"A lot of this depends on the nature of the user of the service. If you are building an application with various classes that use a service, then a dependency from the application classes to the locator isn't a big deal. In my example of giving a Movie Lister to my friends, then using a service locator works quite well. All they need to do is to configure the locator to hook in the right service implementations, either through some configuration code or through a configuration file. In this kind of scenario I don't see the injector's inversion as providing anything compelling."
I would think that for a lot of cases that DDD is used in a nice easy service locator interface will will be enough, of course you could use IoC but it does seem to add a reasonable a reasonable amount of complexity that may not be justified.