Esempio n. 1
0
        private object GetSingleInstance(Type registrationType, object target, string key)
        {
            if (registrationType == null)
            {
                return(null);
            }

            lock (_lock)
            {
                var registrations = _registrations.Where(x => x.RegistrationType == registrationType && x.Key == key);

                var registrationsCount = registrations.Count();
                if (registrationsCount > 1)
                {
                    // More than 1 implementation type registerd for this registration type.
                    // No idea which one to pick.
                    throw new ContainerException(ContainerErrorCodes.MultipleImplementationTypesRegistered,
                                                 $"Cannot get a single instance for registration type {registrationType.FullName} because multiple implementation types have been registered for this registration type.");
                }

                if (registrationsCount == 1)
                {
                    // There is exactly 1 implementation type registered for this registration type.
                    // This is ok, so construct it.
                    var registration = registrations.First();
                    if (registration is TypeRegistrationBase typeRegistration)
                    {
                        return(GetImplementationInstance(typeRegistration, target));
                    }

                    if (registration is HandlerRegistration handlerRegistration)
                    {
                        return(handlerRegistration.Handler(new HandlerParameter(this, target)));
                    }
                }

                return(_containerHelper.GetDefault(registrationType));
            }
        }