Пример #1
0
        protected override void Load(ContainerBuilder builder)
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;

            string[] allKeys = appSettings.AllKeys;
            string[] array   = allKeys;
            for (int i = 0; i < array.Length; i++)
            {
                string text = array[i];
                if (text.Count((char c) => c == '.') == 1)
                {
                    string[] array2 = text.Split(new char[]
                    {
                        '.'
                    });
                    string moduleName = array2[0];
                    string name       = array2[1];
                    string value      = appSettings[text];
                    Module module     = this._modules.FirstOrDefault((Module m) => m.GetType().Name == moduleName + "Module");
                    if (module != null)
                    {
                        PropertyInfo property = module.GetType().GetProperty(name);
                        object       value2   = TypeManipulation.ChangeToCompatibleType(value, property.PropertyType, property);
                        property.SetValue(module, value2, null);
                    }
                }
            }
            foreach (Module current in this._modules)
            {
                ModuleRegistrationExtensions.RegisterModule(builder, current);
            }
        }
Пример #2
0
        /// <summary>
        /// Override to add registrations to the container.
        /// </summary>
        /// <param name="builder">The builder through which components can be registered.</param>
        /// <remarks>
        /// Note that the ContainerBuilder parameter is unique to this module.
        /// </remarks>
        protected override void Load(ContainerBuilder builder)
        {
            var settings = ConfigurationManager.AppSettings;
            var keys     = settings.AllKeys;

            foreach (var setting in keys)
            {
                if (setting.Count(c => c == '.') != 1)
                {
                    continue;
                }

                var parts        = setting.Split('.');
                var moduleName   = parts[0];
                var propertyName = parts[1];
                var value        = settings[setting];

                var module = _modules.FirstOrDefault(m => m.GetType().Name == moduleName + "Module");
                if (module == null)
                {
                    continue;
                }

                var property       = module.GetType().GetProperty(propertyName);
                var convertedValue = TypeManipulation.ChangeToCompatibleType(value, property.PropertyType, property);

                property.SetValue(module, convertedValue, null);
            }

            foreach (var module in _modules)
            {
                builder.RegisterModule(module);
            }
        }
Пример #3
0
            public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
            {
                var instantiatableType = GetInstantiableType(destinationType);

                if (value is DictionaryElementCollection &&
                    instantiatableType != null)
                {
                    var    dictionary = (IDictionary)Activator.CreateInstance(instantiatableType);
                    Type[] generics   = instantiatableType.GetGenericArguments();

                    foreach (var item in (DictionaryElementCollection)value)
                    {
                        if (String.IsNullOrEmpty(item.Key))
                        {
                            throw new ConfigurationErrorsException("Key cannot be null in a dictionary element.");
                        }

                        var convertedKey   = TypeManipulation.ChangeToCompatibleType(item.Key, generics[0]);
                        var convertedValue = TypeManipulation.ChangeToCompatibleType(item.Value, generics[1]);

                        dictionary.Add(convertedKey, convertedValue);
                    }
                    return(dictionary);
                }

                return(base.ConvertTo(context, culture, value, destinationType));
            }
 /// <summary>
 /// Convert to the Autofac parameter type.
 /// </summary>
 /// <returns>The parameters represented by this collection.</returns>
 public IEnumerable <Parameter> ToParameters()
 {
     foreach (var parameter in this)
     {
         var localParameter = parameter;
         yield return(new ResolvedParameter(
                          (pi, c) => pi.Name == localParameter.Name,
                          (pi, c) => TypeManipulation.ChangeToCompatibleType(localParameter.CoerceValue(), pi.ParameterType)));
     }
 }
 /// <summary>
 /// Convert to the Autofac parameter type.
 /// </summary>
 /// <returns>The parameters represented by this collection.</returns>
 public IEnumerable <Parameter> ToParameters()
 {
     foreach (var parameter in this)
     {
         var localParameter = parameter;
         yield return(new ResolvedParameter(
                          (pi, c) =>
         {
             PropertyInfo prop;
             return pi.TryGetDeclaringProperty(out prop) &&
             prop.Name == localParameter.Name;
         },
                          (pi, c) => TypeManipulation.ChangeToCompatibleType(localParameter.CoerceValue(), pi.ParameterType)));
     }
 }
Пример #6
0
            public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
            {
                var instantiatableType = GetInstantiableType(destinationType);

                if (value is ListElementCollection &&
                    instantiatableType != null)
                {
                    Type[] generics = instantiatableType.GetGenericArguments();

                    var collection = (IList)Activator.CreateInstance(instantiatableType);
                    foreach (var item in (ListElementCollection)value)
                    {
                        collection.Add(TypeManipulation.ChangeToCompatibleType(item.Value, generics[0]));
                    }
                    return(collection);
                }

                return(base.ConvertTo(context, culture, value, destinationType));
            }
Пример #7
0
 protected virtual void RegisterConfiguredComponents(ContainerBuilder builder, SectionHandler configurationSection)
 {
     if (builder == null)
     {
         throw new ArgumentNullException("builder");
     }
     if (configurationSection == null)
     {
         throw new ArgumentNullException("configurationSection");
     }
     foreach (ComponentElement current in configurationSection.Components)
     {
         IRegistrationBuilder <object, ConcreteReflectionActivatorData, SingleRegistrationStyle> registrationBuilder = RegistrationExtensions.RegisterType(builder, this.LoadType(current.Type, configurationSection.DefaultAssembly));
         IEnumerable <Service> enumerable = this.EnumerateComponentServices(current, configurationSection.DefaultAssembly);
         foreach (Service current2 in enumerable)
         {
             registrationBuilder.As(new Service[]
             {
                 current2
             });
         }
         foreach (Parameter current3 in current.Parameters.ToParameters())
         {
             RegistrationExtensions.WithParameter <object, ConcreteReflectionActivatorData, SingleRegistrationStyle>(registrationBuilder, current3);
         }
         foreach (Parameter current4 in current.Properties.ToParameters())
         {
             RegistrationExtensions.WithProperty <object, ConcreteReflectionActivatorData, SingleRegistrationStyle>(registrationBuilder, current4);
         }
         foreach (MetadataElement current5 in current.Metadata)
         {
             registrationBuilder.WithMetadata(current5.Name, TypeManipulation.ChangeToCompatibleType(current5.Value, Type.GetType(current5.Type), null));
         }
         if (!string.IsNullOrEmpty(current.MemberOf))
         {
             MemberOf <object, ConcreteReflectionActivatorData, SingleRegistrationStyle>(registrationBuilder, current.MemberOf);
         }
         this.SetLifetimeScope <ConcreteReflectionActivatorData, SingleRegistrationStyle>(registrationBuilder, current.InstanceScope);
         this.SetComponentOwnership <ConcreteReflectionActivatorData, SingleRegistrationStyle>(registrationBuilder, current.Ownership);
         this.SetInjectProperties <ConcreteReflectionActivatorData, SingleRegistrationStyle>(registrationBuilder, current.InjectProperties);
         this.SetAutoActivate <ConcreteReflectionActivatorData, SingleRegistrationStyle>(registrationBuilder, current.AutoActivate);
     }
 }
Пример #8
0
        /// <summary>
        /// Registers individual configured components into a container builder.
        /// </summary>
        /// <param name="builder">
        /// The <see cref="Autofac.ContainerBuilder"/> that should receive the configured registrations.
        /// </param>
        /// <param name="configurationSection">
        /// The <see cref="Autofac.Configuration.SectionHandler"/> containing the configured registrations.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="builder"/> or <paramref name="configurationSection"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="System.Configuration.ConfigurationErrorsException">
        /// Thrown if there is any issue in parsing the component configuration into registrations.
        /// </exception>
        /// <remarks>
        /// <para>
        /// This is where the individually configured component registrations get added to the <paramref name="builder" />.
        /// The <see cref="Autofac.Configuration.SectionHandler.Components"/> collection from the <paramref name="configurationSection" />
        /// get processed into individual registrations with associated lifetime scope, name, etc.
        /// </para>
        /// <para>
        /// You may influence the process by overriding this whole method or by overriding these individual
        /// parsing subroutines:
        /// </para>
        /// <list type="bullet">
        /// <item>
        /// <term><see cref="Autofac.Configuration.ConfigurationRegistrar.SetLifetimeScope"/></term>
        /// </item>
        /// <item>
        /// <term><see cref="Autofac.Configuration.ConfigurationRegistrar.SetComponentOwnership"/></term>
        /// </item>
        /// <item>
        /// <term><see cref="Autofac.Configuration.ConfigurationRegistrar.SetInjectProperties"/></term>
        /// </item>
        /// </list>
        /// </remarks>
        protected virtual void RegisterConfiguredComponents(ContainerBuilder builder, SectionHandler configurationSection)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }
            if (configurationSection == null)
            {
                throw new ArgumentNullException("configurationSection");
            }
            foreach (ComponentElement component in configurationSection.Components)
            {
                var registrar = builder.RegisterType(LoadType(component.Type, configurationSection.DefaultAssembly));

                var services = this.EnumerateComponentServices(component, configurationSection.DefaultAssembly);
                foreach (var service in services)
                {
                    registrar.As(service);
                }
                foreach (var param in component.Parameters.ToParameters())
                {
                    registrar.WithParameter(param);
                }
                foreach (var prop in component.Properties.ToParameters())
                {
                    registrar.WithProperty(prop);
                }
                foreach (var ep in component.Metadata)
                {
                    registrar.WithMetadata(ep.Name, TypeManipulation.ChangeToCompatibleType(ep.Value, Type.GetType(ep.Type), null));
                }
                if (!string.IsNullOrEmpty(component.MemberOf))
                {
                    registrar.MemberOf(component.MemberOf);
                }
                this.SetLifetimeScope(registrar, component.InstanceScope);
                this.SetComponentOwnership(registrar, component.Ownership);
                this.SetInjectProperties(registrar, component.InjectProperties);
                this.SetAutoActivate(registrar, component.AutoActivate);
            }
        }
        /// <summary>
        /// Override to add registrations to the container.
        /// </summary>
        /// <param name="builder">The builder.</param>
        protected override void Load(ContainerBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            Assembly defaultAssembly = null;

            if (!string.IsNullOrEmpty(_sectionHandler.DefaultAssembly))
            {
                defaultAssembly = Assembly.Load(_sectionHandler.DefaultAssembly);
            }

            foreach (ModuleElement moduleElement in _sectionHandler.Modules)
            {
                var moduleType      = LoadType(moduleElement.Type, defaultAssembly);
                var moduleActivator = new ReflectionActivator(
                    moduleType,
                    new BindingFlagsConstructorFinder(BindingFlags.Public),
                    new MostParametersConstructorSelector(),
                    moduleElement.Parameters.ToParameters(),
                    moduleElement.Properties.ToParameters());
                var module = (IModule)moduleActivator.ActivateInstance(Container.Empty, Enumerable.Empty <Parameter>());
                builder.RegisterModule(module);
            }

            foreach (ComponentElement component in _sectionHandler.Components)
            {
                var registrar = builder.RegisterType(LoadType(component.Type, defaultAssembly));

                IList <Service> services = new List <Service>();
                if (!string.IsNullOrEmpty(component.Service))
                {
                    var serviceType = LoadType(component.Service, defaultAssembly);
                    if (!string.IsNullOrEmpty(component.Name))
                    {
                        services.Add(new KeyedService(component.Name, serviceType));
                    }
                    else
                    {
                        services.Add(new TypedService(serviceType));
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(component.Name))
                    {
                        throw new ConfigurationErrorsException(string.Format(
                                                                   ConfigurationSettingsReaderResources.ServiceTypeMustBeSpecified, component.Name));
                    }
                }

                foreach (ServiceElement service in component.Services)
                {
                    var serviceType = LoadType(service.Type, defaultAssembly);
                    if (!string.IsNullOrEmpty(service.Name))
                    {
                        services.Add(new KeyedService(service.Name, serviceType));
                    }
                    else
                    {
                        services.Add(new TypedService(serviceType));
                    }
                }

                foreach (var service in services)
                {
                    registrar.As(service);
                }

                foreach (var param in component.Parameters.ToParameters())
                {
                    registrar.WithParameter(param);
                }

                foreach (var prop in component.Properties.ToParameters())
                {
                    registrar.WithProperty(prop);
                }

                foreach (var ep in component.Metadata)
                {
                    registrar.WithMetadata(
                        ep.Name, TypeManipulation.ChangeToCompatibleType(ep.Value, Type.GetType(ep.Type)));
                }

                if (!string.IsNullOrEmpty(component.MemberOf))
                {
                    registrar.MemberOf(component.MemberOf);
                }

                SetScope(component, registrar);
                SetOwnership(component, registrar);
                SetInjectProperties(component, registrar);
            }

            foreach (FileElement file in _sectionHandler.Files)
            {
                var section = DefaultSectionName;
                if (!string.IsNullOrEmpty(file.Section))
                {
                    section = file.Section;
                }

                var reader = new ConfigurationSettingsReader(section, file.Name);
                builder.RegisterModule(reader);
            }
        }