Exemplo n.º 1
0
        /// <summary>
        /// Resolves the last registered service with a matching name.
        /// </summary>
        /// <typeparam name="TInterface"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        public TInterface Resolve <TInterface>(string name)
        {
            var interfaceType = typeof(TInterface);
            var typeAndName   = new TypeAndName(interfaceType, name);

            Type type;

            if (RegisteredTypes.TryGetValue(typeAndName, out type))
            {
                object lazyInstance;
                if (StoredServices.TryGetValue(typeAndName, out lazyInstance) && lazyInstance.GetType() == typeof(Func <TInterface>))
                {
                    // Lazy singletons must be invoked when called first time.
                    var invokedLazy = ((Func <TInterface>)lazyInstance).Invoke();
                    StoredServices.AddOrUpdate(typeAndName, k => invokedLazy, (k, v) => invokedLazy);
                }

                object instance;
                if (StoredServices.TryGetValue(typeAndName, out instance))
                {
                    // Return the stored singleton object.
                    return((TInterface)instance);
                }

                // Get the first constructor from the registered type.
                var constructor = type.GetConstructors().First();

                // Create a new instance and return it.
                var activator = Common.Activator.GetActivator(constructor);
                return((TInterface)activator());
            }

            return(default(TInterface));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Registers an object as a singleton with a name. When Resolve is called,
        /// the same object is returned.
        /// </summary>
        /// <param name="interfaceType"></param>
        /// <param name="theObject"></param>
        /// <param name="name"></param>
        public void RegisterAsSingleton(Type interfaceType, object theObject, string name)
        {
            var typeAndName = new TypeAndName(interfaceType, name);

            RegisterType(interfaceType, theObject.GetType(), name);
            StoredServices.AddOrUpdate(typeAndName, k => theObject, (k, v) => theObject);
        }