Exemple #1
0
        /// <summary>
        /// Registers an instance in the container using a unique name.
        /// </summary>
        ///
        /// <typeparam name="T">
        /// Type of the instance. Should be an interface.
        /// </typeparam>
        ///
        /// <param name="name">
        /// Unique name to identicate the instance.
        /// </param>
        ///
        /// <param name="instance">
        /// Instance to register.
        /// </param>
        ///
        /// <param name="throwExceptionIfAlreadyRegistered">
        /// Indicates whether an exception is raised on name already used.
        /// </param>
        ///
        /// <returns>
        /// The registered instance.
        /// </returns>
        public T RegisterInstance <T>(string name, T instance, bool throwExceptionIfAlreadyRegistered = true)
        {
            if (string.IsNullOrEmpty(name))
            {
                ThrowException.ThrowArgumentNullException("name");
            }

            T registeredInstance;

            if (this.HasInstance <T>(name, out registeredInstance))
            {
                if (throwExceptionIfAlreadyRegistered)
                {
                    ThrowException.ThrowInvalidOperationException(string.Format(
                                                                      "The instance associated to the '{0}' name is already registered", name));
                }

                return(registeredInstance);
            }
            else
            {
                _container.TryAdd(name, instance);
            }

            return(instance);
        }
Exemple #2
0
        /// <summary>
        /// Parse a value to a enum.
        /// </summary>
        ///
        /// <typeparam name="T">
        /// Type of enum.
        /// </typeparam>
        ///
        /// <param name="value">
        /// Value to parse.
        /// </param>
        ///
        /// <param name="defaultValue">
        /// Default value if the value is null.
        /// </param>
        ///
        /// <returns>
        /// The enum.
        /// </returns>
        public static T ParseByValue <T>(int?value, T defaultValue)
            where T : struct
        {
            if (value == null)
            {
                return(defaultValue);
            }

            if (!Enum.IsDefined(typeof(T), value))
            {
                ThrowException.ThrowInvalidOperationException(string.Format(
                                                                  "The '{0}' enum does not define '{1}' value",
                                                                  typeof(T).ToString(), value));
            }

            return((T)Enum.ToObject(typeof(T), value));
        }