Service Locator example in c#

publicinterfaceICustomer  { string GetCustomerName(); 
  • Implement ICustomer interface.
 classCustomer : ICustomer
    {            publicstring GetCustomerName()          {             return"Customer 1";          	 }      }
  • Create a ServiceLocator as shown below and add the mapping of ICustomer and its real implementation class.
    {         T GetService<T>();     }      	publicclassServiceLocatorSimple : IServiceLocator
    {    	// map that contains pairs of interfaces and
// references to concrete implementations
privateIDictionary<object, object> services;         	 public ServiceLocatorSimple()          {              	services = newDictionary<object, object>();              // fill the map, newCustomer());         }         	 public T GetService<T>()         	 {   try
            {                 	    return (T)services[typeof(T)];               }              catch (KeyNotFoundException)  { thrownewApplicationException("The requested service is not registered"); }          }     }
  • Create a client application to consume it .
 staticvoid Main(string[] args)          {           
  IServiceLocator serviceLocator = newServiceLocatorSimple();     
ICustomer customersaervice = serviceLocator.GetService<ICustomer>();  
 Console.WriteLine(customersaervice.GetCustomerName());          }

Now Client application does not know about the concrete implementation. we can easily change the implementation without effecting 
client application.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s