Skip to content

How to Use

Ken Tucker edited this page Dec 6, 2024 · 1 revision

How to Get classes stored in Dependency Injection with the CommonServiceLocator

GetService

        var serviceType = typeof(IService);
        var result = CommonServiceLocator.ServiceLocator.Current.GetService(serviceType);

This returns a ServiceImpl

GetService< T >

        var result = CommonServiceLocator.ServiceLocator.Current.GetInstance<IService>();

This returns a ServiceImpl

GetInstance(serviceType, key)

        var serviceType = typeof(IPet);
        var key = "Cat";
        var result = CommonServiceLocator.ServiceLocator.Current.GetInstance(serviceType, key);

This returns an instance of Cat

GetInstance< T >(key)

        var key = "Dog";
        var result = CommonServiceLocator.ServiceLocator.Current.GetInstance<IPet>(key);

This returns an instance of Dog

GetInstance(serviceType)

        var serviceType = typeof(IService);
        var result = CommonServiceLocator.ServiceLocator.Current.GetInstance(serviceType);

This returns a ServiceImpl

GetInstance< T >

        var result = CommonServiceLocator.ServiceLocator.Current.GetInstance<IService>();

This returns a ServiceImpl

GetAllInstances(ServiceType)

        var result = CommonServiceLocator.ServiceLocator.Current.GetAllInstances(typeof(IPet));

Will return an IEnumerable that contains a Cat and Dog

GetAllInstances< T >

       var result = CommonServiceLocator.ServiceLocator.Current.GetAllInstances<ICar>()

Will return an IEnumerable that contains a Ford, Chevy and Toyota

Notes

Passing a null in as the key will return the first of the Type registered

        var serviceType = typeof(IPet);
        var result = CommonServiceLocator.ServiceLocator.Current.GetInstance(serviceType, null);

Will return the First IPet registered for DependencyInjection in this case an instance of the Dog class

All examples are based on what is registered in the How to register your services section