Introduction to the ServiceLocator

The ServiceLocator services as the container inside Catel.

Internally it uses the TypeFactory as instantiator for the services.

For more information how types are instantiated and dependency injection, take a look at the TypeFactory documentation

Instantiation styles

The ServiceLocator in Catel supports instantiation style.

What does instantiation style mean?

 Some popular IoC containers support several instantiation styles but they could be summarized into Singleton or Transient. Basically if a type is registered with singleton instantiation style then when the type will be resolved using the IoC container, it will always return the same instance. Otherwise, a new instance is created every time the service is resolved from the IoC container.

Example 1: Registering type into Unity Container with singleton instantiation life style

UnityContainer container = UnityContainer();
container.RegisterType<IPleaseWaitService, PleaseWaitService>(new ContainerControlledLifetimeManager());

Registering a type with instantiation style in Catel

Before Catel 3.3, the ServiceLocator only supported singleton instantiation style, therefore a sequence of a type resolution always has returned the same instance for the requested type.

Now we added a boolean argument to all type registration method family in order to setup if the instantiation style named singleton. We also care about to the Catel's user, therefore the default value of this argument is true, avoiding unexpected application behaviors provoked by a transient instantiation style.

 Example 2: Registering type into the ServiceLocator with transient instantiation life style

ServiceLocator.Instance.RegisterTypeIfNotYetRegistered<IRegionNavigationJournal, RegionNavigationJournal>(false);

External container instantiation style configuration

The ServiceLocator supports synchronization with most of the popular IoC containers, for instance MEF, Unity, Windsor and Ninject. This means that you are able to choose between those container and use one of them as primary one. It is also possible to use on the ServiceLocator of Catel alone. Therefore, if you register an external container into the ServiceLocator and register a type into this external container or into the ServiceLocator, specifying the instantiation style, the instance will be resolved using the right instantiation style.

 Example 3: Resolving a transient instance of IRegionNavigationJournal type from Unity container registered via Catel ServiceLocator

UnityContainer container = container();
ServiceLocator.Instance.RegisterExternalContainer(container);
ServiceLocator.Instance.RegisterType<IRegionNavigationJournal, RegionNavigationJournal>(true, false);
var regionNavigationJournal = container.Resolve<IRegionNavigationJournal>();

Be aware when using MEF as primary container. MEF doesn't support type registration, so it only support singleton instantiation style