ServiceLocator

Package: MyToolkit
Platforms: All (PCL)

A service locator implementation to access service implementations in a decoupled way and to implement dependency injection.

Usage

Register services on application startup:

var service = new ServiceImplementation();
ServiceLocator.Default.RegisterSingleton<IService, ServiceImplementation>(service);

When a service instance is needed, it can be accessed at runtime:

var service = ServiceLocator.Default.Resolve<IService>();

When a service requires another service instance, it should be imported with constructor injection. This method is recommended, because for unit tests the service locater is not needed this way.

public interface IService2
{
    int DoIt();
}

public class Service2Implementation : IService2
{
    private IService _service;

    public Service2Implementation(IService service)
    {
        _service = service; 
    }

    public int DoIt()
    {
        return service.DoIt();
    }
}

When registering IService2 and accessing it with the Resolve method, then the IService object is automatically injected during the IService2 instantiation.

Last edited Jul 28, 2014 at 5:41 PM by rsuter, version 7