Skip to content

How to configure Service Locator

marektihkan edited this page Sep 13, 2010 · 1 revision

Example

Using default registration


ServiceLocator.Register(
   Requested.Service<IService>().IsImplementedBy<Service>());

//Factory
ServiceLocator.Register(
   Requested.Service<IService>()
       .IsConstructedBy(serviceLocator => new Service("a"));

//Generic types
ServiceLocator.Register(
    Requested.Service(typeof(IService<>))
        .IsImplementedBy(typeof(Service<>)));

//With lifestyle
ServiceLocator.Register(
    Requested.Service<IService>()
        .IsImplementedBy<Service>()
        .IsSingleton());

// Lifestyles:
// Is(ServiceLifeStyle); 
// IsTransient(); 
// IsSingleton(); 
// IsOnePerRequest(); 
// IsOnePerThread(); 
// IsOnePerRequestOrThread();

//Multiple registrations
ServiceLocator.Register(
    Requested.Service<IService>().IsImplementedBy<Service>(),
    Requested.Service<IService2>().IsImplementedBy<Service2>()
);

Using module registration


public class LoggingConfiguration : IConfiguration<IServiceLocator>
{
    public static LoggingConfiguration Default()
    {
        return new LoggingConfiguration();
    }

    public void Load(IServiceLocator handler)
    {
        handler.Register(
            Requested.Service<ILog>().IsConstructedBy(x => LogManager.GetLogger("Default")),
            Requested.Service<ILogger>().IsImplementedBy<Logger>()
        );
    }
}

ServiceLocator.Load(LoggingConfiguration.Default());

Using AutoRegistration


ServiceLocator.Load(
    AutoRegistration.For(assemblies)
        .AllConcreteTypes
        .BindToFirstInterface()
);

ServiceLocator.Load(
    AutoRegistration.For(assemblies)
        .Pick(type => type.Name.EndsWith("Controller"))
        .BindToSelf()
);

ServiceLocator.Load(
    AutoRegistration.For(assemblies)
        .AllConcreteTypes
        .BindToInterface(contract => contract.Name.EndsWith("Controller"))
);

ServiceLocator.Load(
    AutoRegistration.For(assemblies)
        .AllConcreteTypes
        .BindToInterface((contract, type) => contract.Name.Contains(type.Name))
        .Using(ServiceLifeStyle.Singleton)
);

Loading specific container modules


var moduleName = "Solution.Configuration.Dependencies.MyNinjectModule"
ServiceLocator.Load(moduleName);

//Ninject: type must be Ninject.IModule

//StructureMap: type must be 
// Arc.Infrastructure.Configuration.IConfiguration<StructureMap.IContainer>

//Castle Windsor: type must be 
// Arc.Infrastructure.Configuration.IConfiguration<Castle.Windsor.IWindsorContainer>