RSS

Category Archives: Design Pattern

Service Locator Pattern/Anti-Pattern?

I was thinking of writing some code on Service Locator pattern until recently I notice loads of resources on the internet state that it is an anti-pattern. Service Locator seems appealing when I first saw it implemented with Unity DI container in Project Silk, a Patterns & Practices article by Microsoft. But the idea of having an global variable like object resolving dependencies rather than just using a DI container bothers me a lot. After reading these arguments, I decided to avoid using Service Locator pattern in MVC.

Here is a thorough introduction of Service Locator and DI by Martin Fowler :
Inversion of Control Containers and the Dependency Injection pattern

These articles point out the cons of Service Locator:
Is IDependencyResolver an anti-pattern?
IoC.Resolve vs Constructor Injection
Service Locator is an Anti-Pattern by Mark Seemann

The purpose of IDependencyResolver in MVC 3 and 4 seems to be supporting legacy codes:
Why is MVC4 using the Service Locator Anti-Pattern
ASP.NET MVC 3 Service Location, Part 5: IDependencyResolver

Read the rest of this entry »

 
Leave a comment

Posted by on June 1, 2012 in .NET, ASP.NET, Design Pattern, MVC3

 

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 »

 
Leave a comment

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

 

Tags: , , , ,