Saturday, September 27, 2014
Dependency Injection Usage
I put together a design to implement a request for a new feature yesterday via DI using an injection framework. Later, while pondering how I came to know about DI and DI frameworks, I realized that I probably would not have gone on that tangent on my own unless something really lead me there. For anyone unfamiliar with DI and/or DI frameworks, the benefits of DI are astounding so definitely learn how to use it. Study SOLID. DI is the D in the SOLID acronym. It means that anything which a particular class is dependent on is injected into the class by something else which knows how to do that. For example, if you have to send an email you could create an EmailManager class that consumes both an IEmailBuilder interface and an IEmailSender interface. The IEmailBuilder would simply have a GetEmail method that returns an Email object. And the IEmailSendable would have a SendEmail method, and possibly a SendEmailAsync method. So you could implement your standard emailing code and use SMTP to send the email. But also, you could send to a message queue such as msmq for some timed process to send batches, or you could write the email to a file or database table. The point is that there are several things you could do with the email. Each should be captured in it's own implementation of IEmailSendable. I smell a Factory pattern coming on here! The pattern of choice for this would be a Factory pattern since we don't know at build time which IEmailSendable to use. In this case, the factory is uses to inject the dependency into the EmailManager. The factory can be used to decide, based on whatever, which implementation of IEmailSendable to inject. This creates a separation of concerns and single responsibility in the classes involved. The EmailManager consumes the IEmailBuilder to get the email, then passes it to the IEmailSendable's Send method to send, file, queue or whatever implementation the Factory injects - perhaps the message delivery method will be looked up in a preferences table for each recipient and the same message will be delivered in different ways! It's all up to the implementation, although I would recommend setting up everything before returning the object from the Factory. It should be ready to send as soo, as SendEmail is called.