It’s so unfortunate that one of the most important features of a DI container that leads to good design can hardly be found on DI products (.Net) today. And the only major one that does support it, is ironically one that is widely considered most inferior in the competition: Microsoft Unity Application Block.
The feature I am talking about is post-instantiation configuration. Or BuildUp() method in Unity. That is, the ability to resolve dependencies of instantiated object. This is the only single feature that stands out as the most interesting aspect I can find from Unity. And by the way, the good design I am talking about, is avoiding Anemic Domain Model.
A class in object-orientation by definition should have both structure and behavior. EJB decided to srew this up by introducing seperation between Session Beans and Entity Beans. Entity beans were fetched from DB, containing only getters and setters, then passed around like cargo between services layers (Session Beans) where all business operations happened.
Dependency Injection came to rescue. Suddenly POJO was becoming the hottest buzzword of the days. Now instead of orderSubmissionService.Submit(order), people found new love to cleaner order.Submit(). Some people even take it further with fluent interface: order.Submit().From(thisStore).NotifyProgressTo(customerEmail).And(agentEmail);
So ideally, the domain object would contain behavior to deal with its own processing and persistence. If domain objects offer such behavior, the service layer will deal with them in object-oriented fashion. Thus, instead of telling OrderSubmissionService to submit an order, the application layer will tell the Order to submit itself.
This makes the code cleaner and easier to maintain. There might still be OrderSubmissionService though, sitting below the skin of Order.Submit(). And we expect DI container to make this OrderSubmissionService accessible for Order instance. Unfortunately, this is where DI containers and ORM today fall short.
Even after the the collapse of EJB era, and with Domain-Driven-Design gaining its fame, the way people architect entities has not changed that much. Today’s DI containers do not even make it easy for an entity to do their job.
Entities are typically instantiated by tools like Hibernate, and thus most DI containers do not support to resolve dependencies for these objects. Preventing our Order entity to do its job. People then end up switching back to the old way by placing business logic in DI-able service layers.
The fact is, this single feature is very easy to implement. My post shows that it won’t take more than few lines of code to make it happens. And I think the Microsoft PnP team has made a really good decision to bring this trivial but important feature.