IServiceLocator non-generic methods.

Dec 16, 2009 at 5:58 PM

Can you add a non-generic implementation of Resolve<T> method to IServiceLocator?

Dec 17, 2009 at 5:31 AM

Yeah, that's doable. One thing I was thinking about is adding some extra functionality around IServiceLocator like instance registration and possible life time support for components.

Dec 17, 2009 at 2:24 PM

Why I`m asking about this, is that I need to add some WCF service in my application, and it has a repository dependency injection. As pointed in this solution , it requires a custom service behaviour and InstanceProvider, which must resolve the dependency through IoC container. For example, in SharpArchitecture:

namespace SharpArch.Wcf
    public class ServiceLocatorInstanceProvider : IInstanceProvider
        public ServiceLocatorInstanceProvider(Type serviceType) {
            this.serviceType = serviceType;

        public object GetInstance(InstanceContext instanceContext) {
            return GetInstance(instanceContext, null);

        /// <summary>
        /// Replicates the behavior of <see cref="SharpArch.Core.SafeServiceLocator" /> 
        /// to create an instance of the requested WCF service.
        /// </summary>
        public object GetInstance(InstanceContext instanceContext, Message message) {
            object service;

            try {
                service = ServiceLocator.Current.GetService(serviceType);
            catch (NullReferenceException) {
                throw new NullReferenceException("ServiceLocator has not been initialized; " +
                    "I was trying to retrieve " + serviceType.ToString());
            catch (ActivationException) {
                throw new ActivationException("The needed dependency of type " + serviceType.Name +
                    " could not be located with the ServiceLocator. You'll need to register it with " +
                    "the Common Service Locator (CSL) via your IoC's CSL adapter.");

            return service;

        public void ReleaseInstance(InstanceContext instanceContext, object instance) { }

        private readonly Type serviceType;
So I can`t make a generic IInstanceProvider<T>, and so I can`t use Resolve<T>. Just what I need is Resolve(Type service).
Dec 17, 2009 at 10:40 PM

Although it is possible to use MVC Turbine as an IoC abstraction for your application, that was not the intent. The IServiceLocator interface was design around the needs for an MVC application, so the method object Resolve(Type service) was not needed. However, the same can be accomplished as follows:


object service = ServiceLocator.Resolve<object>(serviceType);

All what the Resolve<T>(Type) method does is call the underlying Resolve/GetInstance/etc method for the underlying container and casting the resulting object instance to T. So if you set T => object, you'll get your desired result.