示例#1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Factory"/> class.
        /// </summary>
        /// <param name="factories">The underlying factories based on factory contract.</param>
        protected Factory(params IFactory[]  factories)
        {
            _contractDictionary = new Dictionary <Type, IFactory>();
            _productDictionary  = new Dictionary <Type, IFactory>();

            foreach (IFactory factory in factories)
            {
                foreach (Type factoryContract in factory.GetType().GetInterfaces().Where(inter => inter.GetInterfaces().Contains(typeof(IFactory))))
                {
                    _contractDictionary.Add(factoryContract, factory);

                    FactoryContractAttribute attribute = factoryContract.GetCustomAttribute(typeof(FactoryContractAttribute), false) as FactoryContractAttribute;

                    if (attribute != null)
                    {
                        _productDictionary.Add(attribute.Product, factory);
                    }
                }
            }
        }
            /// <summary>
            /// Registers the factory contract.
            /// </summary>
            /// <param name="factoryContract">The factory contract.</param>
            private void RegisterFactoryContract(Type factoryContract, Boolean overwrite)
            {
                if (!overwrite && _container.IsRegistered(factoryContract))
                {
                    return;
                }

                FactoryContractAttribute factoryContractAttribute = factoryContract.GetCustomAttribute(typeof(FactoryContractAttribute), false) as FactoryContractAttribute;

                // the contract can only be registered if the attribute exists
                if (factoryContractAttribute != null)
                {
                    // if a previously registered instance exists, it should be removed
                    if (_container.IsRegisteredInstance(factoryContract))
                    {
                        _container.UnregisterInstance(factoryContract);
                    }

                    _container.Register(factoryContract, factoryContractAttribute.DefaultBehavior, true);
                    _container.Register(factoryContractAttribute.Product.FullName,
                                        factoryContract,
                                        factoryContractAttribute.DefaultBehavior, true);
                }
            }