RSS

Tag Archives: DI

Dependency Injection

I’d like to refactor a simple code sample to demonstrate what dependency injection is. Here I have a MessageSender class to send messages. To send a TextMessage it needs a TextMessage instance.

public class MessageSender
{
    public void SendMessage()
    {
        TextMessage myTextMessage = new TextMessage();
        myTextMessage.Send();
    }
}

public class TextMessage
{
    public void Send()
    {
        // Implements Send()
    }
}

This way the MessageSender depends completely on TextMessage. What if there’s another type named ImageMessage to be sent? I’ll have to modify the SendMessage() method like this:

Read the rest of this entry »

Advertisements
 
Leave a comment

Posted by on April 17, 2012 in .NET, C#, Design Pattern

 

Tags: , , , ,