protected void HandleDecoration(
     IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration,
     bool hasDecorator)
 {
     if (hasDecorator)
     {
         registration.Named(ServiceType.FullName, ServiceType);
     }
     else
     {
         registration.As(ServiceType);
     }
 }
 private static void SetLifetimeScope(ComponentCallModelEnum callModel, IRegistrationBuilder<object, ConcreteReflectionActivatorData, SingleRegistrationStyle> registrationBuilder)
 {
     switch (callModel)
     {
         case ComponentCallModelEnum.Singlecall:
             registrationBuilder.InstancePerDependency();
             break;
         case ComponentCallModelEnum.Singleton:
             registrationBuilder.SingleInstance();
             break;
         default:
             registrationBuilder.InstancePerLifetimeScope();
             break;
     }
 }
Beispiel #3
0
        public void Apply(
            IRegistrationBuilder<object, ConcreteReflectionActivatorData, SingleRegistrationStyle> registration,
            Type dependencyType)
        {
            if (registration == null)
            {
                throw new ArgumentNullException("registration");
            }

            if (dependencyType == null)
            {
                throw new ArgumentNullException("dependencyType");
            }

            registration.AsSelf();
        }
        public void Apply(
            IRegistrationBuilder<object, ConcreteReflectionActivatorData, SingleRegistrationStyle> registration,
            Type dependencyType)
        {
            if (registration == null)
            {
                throw new ArgumentNullException("registration");
            }

            if (dependencyType == null)
            {
                throw new ArgumentNullException("dependencyType");
            }

            foreach (var itf in dependencyType.GetInterfaces().Where(i => i.HasInterface(typeof(ITransientDependency))))
            {
                registration.As(itf).InstancePerDependency();
            }
        }
        private static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> ApplyLifestyleSingle(IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration, Lifestyle lifestyle)
        {
            if (lifestyle.Name == Lifestyle.Singleton.Name)
                return registration.SingleInstance();

            if (lifestyle.Name == Lifestyle.Transient.Name)
                return registration.InstancePerDependency();

            if (lifestyle.Name == Lifestyle.PerWebRequest.Name)
                return registration.InstancePerMatchingLifetimeScope("httpRequest");

            if (lifestyle.Name == Lifestyle.Unmanaged.Name)
                return registration.ExternallyOwned();

            if (lifestyle.Name == Lifestyle.Default.Name)
                return registration.SingleInstance();

            if (lifestyle.Name == Lifestyle.ProviderDefault.Name)
                return registration;

            throw new ArgumentException(string.Format("Unknown lifestyle : {0}", lifestyle), "lifestyle");
        }
Beispiel #6
0
        private static void RegisterPooled <TLimit, TActivatorData, TSingleRegistrationStyle>(
            IRegistrationBuilder <TLimit, TActivatorData, TSingleRegistrationStyle> registration,
            IPooledRegistrationPolicy <TLimit> registrationPolicy,
            object[]?tags)
            where TSingleRegistrationStyle : SingleRegistrationStyle
            where TActivatorData : IConcreteActivatorData
            where TLimit : class
        {
            if (registration == null)
            {
                throw new ArgumentNullException(nameof(registration));
            }

            // Mark the lifetime appropriately.
            var regData = registration.RegistrationData;

            regData.Lifetime = new PooledLifetime();
            regData.Sharing  = InstanceSharing.None;

            var callback = regData.DeferredCallback;

            if (callback is null)
            {
                throw new NotSupportedException(RegistrationExtensionsResources.RequiresCallbackContainer);
            }

            if (registration.ActivatorData.Activator is ProvidedInstanceActivator)
            {
                // Can't use provided instance activators with pooling (because it would try to repeatedly activate).
                throw new NotSupportedException(RegistrationExtensionsResources.CannotUseProvidedInstances);
            }

            var original = callback.Callback;

            Action <IComponentRegistryBuilder> newCallback = registry =>
            {
                // Only do the additional registrations if we are still using a PooledLifetime.
                if (!(regData.Lifetime is PooledLifetime))
                {
                    original(registry);
                    return;
                }

                var pooledInstanceService = new UniqueService();

                var instanceActivator = registration.ActivatorData.Activator;

                if (registration.ResolvePipeline.Middleware.Any(c => c is CoreEventMiddleware ev && ev.EventType == ResolveEventType.OnRelease))
                {
                    // OnRelease shouldn't be used with pooled instances, because if a policy chooses not to return them to the pool,
                    // the Disposal will be fired, not the OnRelease call; this means that OnRelease wouldn't fire until the container is disposed,
                    // which is not what we want.
                    throw new NotSupportedException(RegistrationExtensionsResources.OnReleaseNotSupported);
                }

                // First, we going to create a pooled instance activator, that will be resolved when we want to
                // **actually** resolve a new instance (during 'Create').
                // The instances themselves are owned by the pool, and will be disposed when the pool disposes
                // (or when the instance is not returned to the pool).
                var pooledInstanceRegistration = new ComponentRegistration(
                    Guid.NewGuid(),
                    instanceActivator,
                    RootScopeLifetime.Instance,
                    InstanceSharing.None,
                    InstanceOwnership.ExternallyOwned,
                    registration.ResolvePipeline,
                    new[] { pooledInstanceService },
                    new Dictionary <string, object?>());

                registry.Register(pooledInstanceRegistration);

                var poolService = new PoolService(pooledInstanceRegistration);

                var poolRegistration = new ComponentRegistration(
                    Guid.NewGuid(),
                    new PoolActivator <TLimit>(pooledInstanceService, registrationPolicy),
                    RootScopeLifetime.Instance,
                    InstanceSharing.Shared,
                    InstanceOwnership.OwnedByLifetimeScope,
                    new[] { poolService },
                    new Dictionary <string, object?>());

                registry.Register(poolRegistration);

                var pooledGetLifetime = tags is null ? CurrentScopeLifetime.Instance : new MatchingScopeLifetime(tags);

                // Next, create a new registration with a custom activator, that copies metadata and services from
                // the original registration. This registration will access the pool and return an instance from it.
                var poolGetRegistration = new ComponentRegistration(
                    Guid.NewGuid(),
                    new PoolGetActivator <TLimit>(poolService, registrationPolicy),
                    pooledGetLifetime,
                    InstanceSharing.Shared,
                    InstanceOwnership.OwnedByLifetimeScope,
                    regData.Services,
                    regData.Metadata);

                registry.Register(poolGetRegistration);

                // Finally, add a service pipeline stage to just before the sharing middleware, for each supported service, to extract the pooled instance from the pool instance container.
                foreach (var srv in regData.Services)
                {
                    registry.RegisterServiceMiddleware(srv, new PooledInstanceUnpackMiddleware <TLimit>(), MiddlewareInsertionMode.StartOfPhase);
                }
            };

            callback.Callback = newCallback;
        }
Beispiel #7
0
 WithOrder <TLimit, TActivatorData, TRegistrationStyle>(
     this IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> registrationBuilder) =>
 registrationBuilder.WithMetadata(OrderString, Interlocked.Increment(ref orderCounter));
 protected void HandleDecoration(
     IRegistrationBuilder<object, ReflectionActivatorData, DynamicRegistrationStyle> registration,
     bool hasDecorator)
 {
     if (hasDecorator)
     {
         registration.Named(ServiceType.FullName, ServiceType);
     }
     else
     {
         registration.As(ServiceType);
     }
 }
Beispiel #9
0
 public static IRegistrationBuilder <TLimit, TActivatorData, TSingleRegistrationStyle> MemberOf <TLimit, TActivatorData, TSingleRegistrationStyle>(IRegistrationBuilder <TLimit, TActivatorData, TSingleRegistrationStyle> registration, string collectionName) where TSingleRegistrationStyle : SingleRegistrationStyle
 {
     if (registration == null)
     {
         throw new ArgumentNullException("registration");
     }
     Enforce.ArgumentNotNull(collectionName, "collectionName");
     registration.OnRegistered <TLimit, TActivatorData, TSingleRegistrationStyle>(delegate(ComponentRegisteredEventArgs e)
     {
         IDictionary <string, object> metadata = e.ComponentRegistration.Metadata;
         if (metadata.ContainsKey("Autofac.CollectionRegistrationExtensions.MemberOf"))
         {
             metadata["Autofac.CollectionRegistrationExtensions.MemberOf"] = ((IEnumerable <string>)metadata["Autofac.CollectionRegistrationExtensions.MemberOf"]).Union <string>(new string[] { collectionName });
         }
         else
         {
             metadata.Add("Autofac.CollectionRegistrationExtensions.MemberOf", new string[] { collectionName });
         }
     });
     return(registration);
 }
Beispiel #10
0
        protected virtual void SetAutoActivate <TReflectionActivatorData, TSingleRegistrationStyle>(IRegistrationBuilder <object, TReflectionActivatorData, TSingleRegistrationStyle> registrar, string autoActivate) where TReflectionActivatorData : ReflectionActivatorData where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (registrar == null)
            {
                throw new ArgumentNullException("registrar");
            }
            if (string.IsNullOrWhiteSpace(autoActivate))
            {
                return;
            }
            string key;

            switch (key = autoActivate.Trim().ToUpperInvariant())
            {
            case "NO":
            case "N":
            case "FALSE":
            case "0":
                return;

            case "YES":
            case "Y":
            case "TRUE":
            case "1":
                RegistrationExtensions.AutoActivate <object, TReflectionActivatorData, TSingleRegistrationStyle>(registrar);
                return;
            }
            throw new ConfigurationErrorsException(string.Format(CultureInfo.CurrentCulture, ConfigurationSettingsReaderResources.UnrecognisedAutoActivate, new object[]
            {
                autoActivate
            }));
        }
Beispiel #11
0
        /// <summary>
        /// 根据组件的生命周期定义注册组件
        /// </summary>
        /// <param name="buidler">Autofac的IContainer对象</param>
        /// <param name="assemblies">注册的程序集</param>
        /// <returns>Autofac的注册构造器枚举</returns>
        public static IEnumerable <IRegistrationBuilder <object, Autofac.Features.Scanning.ScanningActivatorData, DynamicRegistrationStyle> > RegisterAssemblyTypesWithLiftTimeScope(this ContainerBuilder buidler, params Assembly[] assemblies)
        {
            IEnumerable <IRegistrationBuilder <object, Autofac.Features.Scanning.ScanningActivatorData, DynamicRegistrationStyle> > builders =
                new IRegistrationBuilder <object, Autofac.Features.Scanning.ScanningActivatorData, DynamicRegistrationStyle>[] {
                //瞬态
                buidler.RegisterAssemblyTypes(assemblies).Where(m => ComponentRegistryAttribute.ValidateType(m, Lifetime.Transient)).InstancePerDependency(),
                //单例
                buidler.RegisterAssemblyTypes(assemblies).Where(m => ComponentRegistryAttribute.ValidateType(m, Lifetime.Singleton)).SingleInstance(),
                //容器
                buidler.RegisterAssemblyTypes(assemblies).Where(m => ComponentRegistryAttribute.ValidateType(m, Lifetime.Container)).InstancePerLifetimeScope(),
            };

            return(builders);
        }
Beispiel #12
0
 /// <summary>
 /// Enable interface interception on the target type. Interceptors will be determined
 /// via Intercept attributes on the class or interface, or added with InterceptedBy() calls.
 /// </summary>
 /// <typeparam name="TLimit">Registration limit type.</typeparam>
 /// <typeparam name="TActivatorData">Activator data type.</typeparam>
 /// <typeparam name="TSingleRegistrationStyle">Registration style.</typeparam>
 /// <param name="registration">Registration to apply interception to.</param>
 /// <returns>Registration builder allowing the registration to be configured.</returns>
 public static IRegistrationBuilder <TLimit, TActivatorData, TSingleRegistrationStyle> EnableInterfaceInterceptors <TLimit, TActivatorData, TSingleRegistrationStyle>(
     this IRegistrationBuilder <TLimit, TActivatorData, TSingleRegistrationStyle> registration)
 {
     return(EnableInterfaceInterceptors(registration, null));
 }
Beispiel #13
0
        /// <summary>
        /// Sets the auto activation mode for the component.
        /// </summary>
        /// <param name="component">
        /// The configuration data containing the component. The <c>autoActivate</c>
        /// content will be read from this configuration object and used
        /// to determine auto activation status.
        /// </param>
        /// <param name="registrar">
        /// The component registration on which auto activation mode is being set.
        /// </param>
        /// <remarks>
        /// <para>
        /// By default, this implementation understands <see langword="null"/>, empty,
        /// or <see langword="false"/> values (<c>false</c>, <c>0</c>, <c>no</c>)
        /// to mean "not auto-activated" and <see langword="true"/>
        /// values (<c>true</c>, <c>1</c>, <c>yes</c>) to mean "auto activation
        /// should occur."
        /// </para>
        /// <para>
        /// You may override this method to extend the available grammar for auto activation settings.
        /// </para>
        /// </remarks>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="registrar"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// Thrown if the value for <c>autoActivate</c> is not part of the
        /// recognized grammar.
        /// </exception>
        protected virtual void SetAutoActivate<TReflectionActivatorData, TSingleRegistrationStyle>(IConfiguration component, IRegistrationBuilder<object, TReflectionActivatorData, TSingleRegistrationStyle> registrar)
            where TReflectionActivatorData : ReflectionActivatorData
            where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            if (component["autoActivate"].ToFlexibleBoolean())
            {
                registrar.AutoActivate();
            }
        }
Beispiel #14
0
        /// <summary>
        /// Sets the ownership model for the component.
        /// </summary>
        /// <param name="component">
        /// The configuration data containing the component. The <c>ownership</c>
        /// content will be read from this configuration object and used
        /// to determine component ownership.
        /// </param>
        /// <param name="registrar">
        /// The component registration on which component ownership is being set.
        /// </param>
        /// <remarks>
        /// <para>
        /// By default, this implementation understands <see langword="null"/> or empty
        /// values to be "default ownership model"; <c>lifetime-scope</c> or <c>LifetimeScope</c>
        /// is "owned by lifetime scope"; and <c>external</c> or <c>ExternallyOwned</c> is
        /// "externally owned."
        /// </para>
        /// <para>
        /// By default, this implementation understands the following grammar:
        /// </para>
        /// <list type="table">
        /// <listheader>
        /// <term>Values</term>
        /// <description>Lifetime Scope</description>
        /// </listheader>
        /// <item>
        /// <term><see langword="null"/>, empty</term>
        /// <description>Default - no specified ownership model</description>
        /// </item>
        /// <item>
        /// <term><c>lifetime-scope</c>, <c>LifetimeScope</c></term>
        /// <description>Owned by lifetime scope</description>
        /// </item>
        /// <item>
        /// <term><c>external</c>, <c>ExternallyOwned</c></term>
        /// <description>Externally owned</description>
        /// </item>
        /// </list>
        /// <para>
        /// You may override this method to extend the available grammar for component ownership.
        /// </para>
        /// </remarks>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="registrar"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// Thrown if the value for <c>ownership</c> is not part of the
        /// recognized grammar.
        /// </exception>
        protected virtual void SetComponentOwnership<TReflectionActivatorData, TSingleRegistrationStyle>(IConfiguration component, IRegistrationBuilder<object, TReflectionActivatorData, TSingleRegistrationStyle> registrar)
            where TReflectionActivatorData : ReflectionActivatorData
            where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            string ownership = component["ownership"];
            if (string.IsNullOrWhiteSpace(ownership))
            {
                return;
            }

            ownership = ownership.Trim().Replace("-", "");
            if (ownership.Equals("lifetimescope", StringComparison.OrdinalIgnoreCase))
            {
                registrar.OwnedByLifetimeScope();
                return;
            }

            if (ownership.Equals("external", StringComparison.OrdinalIgnoreCase) ||
                ownership.Equals("externallyowned", StringComparison.OrdinalIgnoreCase))
            {
                registrar.ExternallyOwned();
                return;
            }

            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ConfigurationResources.UnrecognisedOwnership, ownership));
        }
Beispiel #15
0
        /// <summary>
        /// Reads configuration data for a component's configured property values
        /// and updates the component registration as needed.
        /// </summary>
        /// <param name="component">
        /// The configuration data containing the component. The <c>properties</c>
        /// content will be read from this configuration object and used
        /// as the properties to inject.
        /// </param>
        /// <param name="registrar">
        /// The component registration to update with property injection.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="component" /> or <paramref name="registrar" /> is <see langword="null" />.
        /// </exception>
        protected virtual void RegisterComponentProperties<TReflectionActivatorData, TSingleRegistrationStyle>(IConfiguration component, IRegistrationBuilder<object, TReflectionActivatorData, TSingleRegistrationStyle> registrar)
            where TReflectionActivatorData : ReflectionActivatorData
            where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (component == null)
            {
                throw new ArgumentNullException(nameof(component));
            }

            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            foreach (var prop in component.GetProperties("properties"))
            {
                registrar.WithProperty(prop);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Reads configuration data for a component's exposed services
        /// and updates the component registration as needed.
        /// </summary>
        /// <param name="component">
        /// The configuration data containing the component. The <c>services</c>
        /// content will be read from this configuration object and used
        /// as the services.
        /// </param>
        /// <param name="registrar">
        /// The component registration to update with services.
        /// </param>
        /// <param name="defaultAssembly">
        /// The default assembly, if any, from which unqualified type names
        /// should be resolved into types.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="component" /> or <paramref name="registrar" /> is <see langword="null" />.
        /// </exception>
        protected virtual void RegisterComponentServices<TReflectionActivatorData, TSingleRegistrationStyle>(IConfiguration component, IRegistrationBuilder<object, TReflectionActivatorData, TSingleRegistrationStyle> registrar, Assembly defaultAssembly)
            where TReflectionActivatorData : ReflectionActivatorData
            where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (component == null)
            {
                throw new ArgumentNullException(nameof(component));
            }

            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            foreach (var service in this.EnumerateComponentServices(component, defaultAssembly))
            {
                registrar.As(service);
            }
        }
Beispiel #17
0
        /// <summary>
        /// Reads configuration data for a component's metadata
        /// and updates the component registration as needed.
        /// </summary>
        /// <param name="component">
        /// The configuration data containing the component. The <c>metadata</c>
        /// content will be read from this configuration object and used
        /// as the metadata values.
        /// </param>
        /// <param name="registrar">
        /// The component registration to update with metadata.
        /// </param>
        /// <param name="defaultAssembly">
        /// The default assembly, if any, from which unqualified type names
        /// should be resolved into types.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="component" /> or <paramref name="registrar" /> is <see langword="null" />.
        /// </exception>
        protected virtual void RegisterComponentMetadata<TReflectionActivatorData, TSingleRegistrationStyle>(IConfiguration component, IRegistrationBuilder<object, TReflectionActivatorData, TSingleRegistrationStyle> registrar, Assembly defaultAssembly)
            where TReflectionActivatorData : ReflectionActivatorData
            where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (component == null)
            {
                throw new ArgumentNullException(nameof(component));
            }

            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            foreach (var ep in component.GetSection("metadata").GetChildren())
            {
                registrar.WithMetadata(ep["key"], TypeManipulation.ChangeToCompatibleType(ep["value"], ep.GetType("type", defaultAssembly)));
            }
        }
Beispiel #18
0
 /// <summary>
 /// Sets the property injection on a registration based on options.
 /// </summary>
 /// <typeparam name="TLimit">The most specific type to which instances of the registration
 /// can be cast.</typeparam>
 /// <typeparam name="TActivatorData">Activator builder type.</typeparam>
 /// <typeparam name="TRegistrationStyle">Registration style type.</typeparam>
 /// <param name="registration">The registration to update.</param>
 /// <exception cref="System.ArgumentNullException">
 /// Thrown if <paramref name="registration" /> is <see langword="null" />.
 /// </exception>
 protected virtual void SetPropertyInjection <TLimit, TActivatorData, TRegistrationStyle>(IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> registration)
 {
     this.provider.SetPropertyInjection(registration);
 }
Beispiel #19
0
 public static void ApplyDefaultPerRequestConfiguration(this IRegistrationBuilder <object, object, object> registrationBuilder, AppStart config, bool dontAllowCircularDependencies = false)
 {
     registrationBuilder.ApplyDefaultConfiguration(config.LifetimeScopeConfigurator, dontAllowCircularDependencies);
 }
        protected override void Load(ContainerBuilder builder)
        {
            Contract.Assert(builder != null, "Builder container is null");

            builder.RegisterType <FoundationConfigurationSection>().As <IFoundationConfigurationSection>()
            .ExternallyOwned();

            var configSection = ConfigurationManager.GetSection("rebel.foundation") as IFoundationConfigurationSection;

            builder.RegisterInstance(configSection)
            .As <IFoundationConfigurationSection>()
            .ExternallyOwned()
            .SingleInstance();

            foreach (PersistenceProviderElement element in configSection.PersistenceProviders)
            {
                IList <Service> services = new List <Service>();

                // Resolve the type itself
                Type implementationType = ConfigurationExtensions.GetTypeFromTypeConfigName(element.Type);

                // Offer to invoke the provider's setup module (if any exist)
                builder.RegisterModule(new ProviderAutoSetupModule(implementationType.Assembly, element.Key));

                IRegistrationBuilder <object, ConcreteReflectionActivatorData, SingleRegistrationStyle>
                providerRegistrar = builder
                                    .RegisterType(implementationType)
                                    .Named <IPersistenceManager>(element.Key)
                                    .SingleInstance();

                // Resolve the reader type from config
                Type   readerType        = ConfigurationExtensions.GetTypeFromTypeConfigName(element.Reader.Type);
                string compoundReaderKey = string.Format("{0}/{1}", element.Key, element.Reader.Key);

                // Overwrite the configuration key so that it is a compound of the reader and its parent provider
                element.Reader.InternalKey = compoundReaderKey;

                // Register the reader with IoC against the interface
                builder.RegisterType(readerType)
                // Name this registration
                .Named <IPersistenceReadWriter>(compoundReaderKey)
                // Allow passing in a named constructor parameter for the alias
                .WithParameter(new NamedParameter("alias", element.Reader.InternalKey))
                // Allow passing in a resolved ITypeMapper
                .WithParameter(GenerateResolvedParameter <ITypeMapper>())
                // Allow passing in a resolved IUnitOfWork
                .WithParameter(GenerateResolvedParameter <IUnitOfWork>());

                // Register the reader with IoC against the concrete type declared in config too
                // TODO: There's a way to do this in one call with Autofac ;)
                builder.RegisterType(readerType)
                .Named(compoundReaderKey, readerType)
                .WithParameter(new NamedParameter("alias", element.Reader.InternalKey))
                .WithParameter(GenerateResolvedParameter <ITypeMapper>())
                .WithParameter(GenerateResolvedParameter <IUnitOfWork>());

                providerRegistrar.WithParameter(element.Reader.ToParameter());

                foreach (PersistenceReadWriterElement readWriter in element.ReadWriters)
                {
                    Type repoType = ConfigurationExtensions.GetTypeFromTypeConfigName(readWriter.Type);

                    string compoundRepositoryKey = string.Format("{0}/{1}", element.Key, readWriter.Key);

                    // Overwrite the configuration key so that it is a compound of the read-writer and its parent provider
                    readWriter.InternalKey = compoundRepositoryKey;

                    builder
                    .RegisterType(repoType)
                    .Named <IPersistenceReadWriter>(compoundRepositoryKey)
                    .WithParameter(new NamedParameter("alias", readWriter.InternalKey))
                    .WithParameter(GenerateResolvedParameter <ITypeMapper>())
                    .WithParameter(GenerateResolvedParameter <IUnitOfWork>());

                    builder
                    .RegisterType(repoType)
                    .Named(compoundRepositoryKey, repoType)
                    .WithParameter(new NamedParameter("alias", readWriter.InternalKey))
                    .WithParameter(GenerateResolvedParameter <ITypeMapper>())
                    .WithParameter(GenerateResolvedParameter <IUnitOfWork>());
                }

                //TODO: This only works at the moment because the two test providers accept one ReadWriter and we're only declaring
                //one in config. Need to refactor providers to accept a list of read-writers to complete the chaining refactor
                foreach (Parameter param in element.ReadWriters.ToParameters())
                {
                    providerRegistrar.WithParameter(param);
                }

                providerRegistrar.WithParameter(new TypedParameter(typeof(string), element.Key));
            }
        }
Beispiel #21
0
        /// <summary>
        /// Sets the property injection mode for the component.
        /// </summary>
        /// <param name="component">
        /// The configuration data containing the component. The <c>injectProperties</c>
        /// content will be read from this configuration object and used
        /// to determine property injection status.
        /// </param>
        /// <param name="registrar">
        /// The component registration on which the property injection mode is being set.
        /// </param>
        /// <remarks>
        /// <para>
        /// By default, this implementation understands <see langword="null"/>, empty,
        /// or <see langword="false"/> values (<c>false</c>, <c>0</c>, <c>no</c>)
        /// to mean "no property injection" and <see langword="true"/>
        /// values (<c>true</c>, <c>1</c>, <c>yes</c>) to mean "property injection
        /// should occur."
        /// </para>
        /// <para>
        /// You may override this method to extend the available grammar for property injection settings.
        /// </para>
        /// </remarks>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="registrar"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// Thrown if the value for <c>injectProperties</c> is not part of the
        /// recognized grammar.
        /// </exception>
        protected virtual void SetInjectProperties<TReflectionActivatorData, TSingleRegistrationStyle>(IConfiguration component, IRegistrationBuilder<object, TReflectionActivatorData, TSingleRegistrationStyle> registrar)
            where TReflectionActivatorData : ReflectionActivatorData
            where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            if (component["injectProperties"].ToFlexibleBoolean())
            {
                registrar.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
            }
        }
Beispiel #22
0
 public static IRegistrationBuilder <TLimit, TReflectionActivatorData, TStyle> WithNullCache <TLimit, TReflectionActivatorData, TStyle>(this IRegistrationBuilder <TLimit, TReflectionActivatorData, TStyle> registration) where TReflectionActivatorData : ReflectionActivatorData
 {
     return(registration.WithParameter(Autofac.Core.ResolvedParameter.ForNamed <ICacheManager>("null")));
 }
Beispiel #23
0
        protected virtual void SetLifetimeScope<TReflectionActivatorData, TSingleRegistrationStyle>(IConfiguration component, IRegistrationBuilder<object, TReflectionActivatorData, TSingleRegistrationStyle> registrar)
            where TReflectionActivatorData : ReflectionActivatorData
            where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            string lifetimeScope = component["instanceScope"];
            if (string.IsNullOrWhiteSpace(lifetimeScope))
            {
                return;
            }

            lifetimeScope = lifetimeScope.Trim().Replace("-", "");
            if (lifetimeScope.Equals("singleinstance", StringComparison.OrdinalIgnoreCase))
            {
                registrar.SingleInstance();
                return;
            }

            if (lifetimeScope.Equals("instanceperlifetimescope", StringComparison.OrdinalIgnoreCase) ||
                lifetimeScope.Equals("perlifetimescope", StringComparison.OrdinalIgnoreCase))
            {
                registrar.InstancePerLifetimeScope();
                return;
            }

            if (lifetimeScope.Equals("instanceperdependency", StringComparison.OrdinalIgnoreCase) ||
                lifetimeScope.Equals("perdependency", StringComparison.OrdinalIgnoreCase))
            {
                registrar.InstancePerDependency();
                return;
            }

            if (lifetimeScope.Equals("instanceperrequest", StringComparison.OrdinalIgnoreCase) ||
                lifetimeScope.Equals("perrequest", StringComparison.OrdinalIgnoreCase))
            {
                registrar.InstancePerRequest();
                return;
            }

            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ConfigurationResources.UnrecognisedScope, lifetimeScope));
        }
Beispiel #24
0
    public static IRegistrationBuilder <TLimit, TConcreteActivatorData, SingleRegistrationStyle> AsQueryHandler <TLimit, TConcreteActivatorData>(this IRegistrationBuilder <TLimit, TConcreteActivatorData, SingleRegistrationStyle> registration)
        where TConcreteActivatorData : IConcreteActivatorData
    {
        Type queryHandlerType             = registration.ActivatorData.Activator.LimitType;
        Type queryHandlerRegistrationType = queryHandlerType.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IQueryHandlerAsync <,>));

        if (queryHandlerRegistrationType == null)
        {
            throw new ArgumentException($"{queryHandlerType} doesn't implement {typeof(IQueryHandlerAsync<,>).Name} interface");
        }
        TypedService queryHandlerService = new TypedService(queryHandlerRegistrationType);

        return(registration.As(queryHandlerService));
    }
 public static IRegistrationBuilder <TLimit, TActivatorData, TStyle> EnableParametersValidation <TLimit, TActivatorData, TStyle>(
     this IRegistrationBuilder <TLimit, TActivatorData, TStyle> builder) =>
 builder.InterceptedBy(typeof(ValidationInterceptor));
Beispiel #26
0
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="TLimit"></typeparam>
 /// <typeparam name="TConcreteReflectionActivatorData"></typeparam>
 /// <typeparam name="TRegistrationStyle"></typeparam>
 /// <param name="registration"></param>
 /// <param name="additionalInterfaces"></param>
 /// <returns></returns>
 public static IRegistrationBuilder <TLimit, TConcreteReflectionActivatorData, TRegistrationStyle> EnableClassInterceptors <TLimit, TConcreteReflectionActivatorData, TRegistrationStyle>(
     this IRegistrationBuilder <TLimit, TConcreteReflectionActivatorData, TRegistrationStyle> registration, params Type[] additionalInterfaces)
     where TConcreteReflectionActivatorData : ReflectionActivatorData
 {
     return(EnableClassInterceptors(registration, ProxyGenerationOptions.Default, additionalInterfaces));
 }
        public static IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> RegisterServiceBus
        (
            this ContainerBuilder builder)
        {
            var referenceAssemblies = builder.GetReferenceAssembly();
            IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> result = null;
            var assemblies = referenceAssemblies.Where(
                p =>
                p.GetCustomAttribute <AssemblyModuleTypeAttribute>().Type == ModuleType.BusinessModule ||
                p.GetCustomAttribute <AssemblyModuleTypeAttribute>().Type == ModuleType.Domain).ToList();

            foreach (var assembly in assemblies)
            {
                result = builder.RegisterAssemblyTypes(assembly)
                         .Where(t => typeof(IIntegrationEventHandler).GetTypeInfo().IsAssignableFrom(t)).AsImplementedInterfaces().SingleInstance();
                result = builder.RegisterAssemblyTypes(assembly)
                         .Where(t => typeof(IIntegrationEventHandler).IsAssignableFrom(t)).SingleInstance();
            }
            return(result);
        }
Beispiel #28
0
        protected virtual void SetInjectProperties <TReflectionActivatorData, TSingleRegistrationStyle>(IRegistrationBuilder <object, TReflectionActivatorData, TSingleRegistrationStyle> registrar, string injectProperties) where TReflectionActivatorData : ReflectionActivatorData where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (registrar == null)
            {
                throw new ArgumentNullException("registrar");
            }
            if (string.IsNullOrWhiteSpace(injectProperties))
            {
                return;
            }
            string key;

            switch (key = injectProperties.Trim().ToUpperInvariant())
            {
            case "NO":
            case "N":
            case "FALSE":
            case "0":
                return;

            case "YES":
            case "Y":
            case "TRUE":
            case "1":
                registrar.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
                return;
            }
            throw new ConfigurationErrorsException(string.Format(CultureInfo.CurrentCulture, ConfigurationSettingsReaderResources.UnrecognisedInjectProperties, new object[]
            {
                injectProperties
            }));
        }
        private static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> ApplyName(IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration, string name, Type service)
        {
            if (string.IsNullOrEmpty(name))
                return registration;

            return registration.Named(name, service);
        }
Beispiel #30
0
        protected virtual void SetComponentOwnership <TReflectionActivatorData, TSingleRegistrationStyle>(IRegistrationBuilder <object, TReflectionActivatorData, TSingleRegistrationStyle> registrar, string ownership) where TReflectionActivatorData : ReflectionActivatorData where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (registrar == null)
            {
                throw new ArgumentNullException("registrar");
            }
            if (string.IsNullOrWhiteSpace(ownership))
            {
                return;
            }
            string a;

            if ((a = ownership.Trim().ToUpperInvariant()) != null)
            {
                if (a == "LIFETIME-SCOPE" || a == "LIFETIMESCOPE")
                {
                    registrar.OwnedByLifetimeScope();
                    return;
                }
                if (a == "EXTERNAL" || a == "EXTERNALLYOWNED")
                {
                    registrar.ExternallyOwned();
                    return;
                }
            }
            throw new ConfigurationErrorsException(string.Format(CultureInfo.CurrentCulture, ConfigurationSettingsReaderResources.UnrecognisedOwnership, new object[]
            {
                ownership
            }));
        }
 InstancePerProfilerSession <TLimit, TActivatorData, TRegistrationStyle>(this IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> builder)
 {
     return(builder.InstancePerMatchingLifetimeScope(Constants.ProfilerSessionScopeTag));
 }
 private static void SetLifetimeScope(DependencyLifecycle dependencyLifecycle, IRegistrationBuilder<object, ConcreteReflectionActivatorData, SingleRegistrationStyle> registrationBuilder)
 {
     switch (dependencyLifecycle)
     {
         case DependencyLifecycle.InstancePerCall:
             registrationBuilder.InstancePerDependency();
             break;
         case DependencyLifecycle.SingleInstance:
             registrationBuilder.SingleInstance();
             break;
         case DependencyLifecycle.InstancePerUnitOfWork:
             registrationBuilder.InstancePerLifetimeScope();
             break;
         default:
             throw new ArgumentException("Unhandled lifecycle - " + dependencyLifecycle);
     }
 }
        public static IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> RegisterServices(
            this ContainerBuilder builder)
        {
            var referenceAssemblies = builder.GetReferenceAssembly();
            IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> result = null;

            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            #region 接口服务注入
            var interfaceAssemblies = referenceAssemblies.Where(
                p =>
                p.GetCustomAttribute <AssemblyModuleTypeAttribute>().Type == ModuleType.InterFaceService ||
                p.GetCustomAttribute <AssemblyModuleTypeAttribute>().Type == ModuleType.SystemModule).ToList();
            foreach (var interfaceAssembly in interfaceAssemblies)
            {
                result = builder.RegisterAssemblyTypes(interfaceAssembly)
                         .Where(t => t.Name.StartsWith("I")).Where(t => t.Name.EndsWith("Service"))
                         .AsImplementedInterfaces();
            }
            #endregion

            #region 领域服务注入
            var domainAssemblies = referenceAssemblies.Where(
                p =>
                p.GetCustomAttribute <AssemblyModuleTypeAttribute>().Type == ModuleType.BusinessModule ||
                p.GetCustomAttribute <AssemblyModuleTypeAttribute>().Type == ModuleType.Domain).ToList();
            foreach (var domainAssembly in domainAssemblies)
            {
                result = builder.RegisterAssemblyTypes(domainAssembly)
                         .Where(t => t.Name.EndsWith("Service") && t.GetTypeInfo().GetCustomAttribute <ModuleNameAttribute>() == null).AsImplementedInterfaces();
                //  result = builder.RegisterAssemblyTypes(domainAssembly)
                //.Where(t => t.Name.EndsWith("Service") && t.GetTypeInfo().GetCustomAttribute<ModuleNameAttribute>() == null).EnableClassInterceptors();
                var types = domainAssembly.GetTypes().Where(t => t.Name.EndsWith("Service") && t.GetTypeInfo().GetCustomAttribute <ModuleNameAttribute>() != null);
                foreach (var type in types)
                {
                    var module       = type.GetTypeInfo().GetCustomAttribute <ModuleNameAttribute>();
                    var interfaceObj = type.GetInterfaces()
                                       .FirstOrDefault(t => t.Name.StartsWith("I") && t.Name.EndsWith("Service"));
                    if (interfaceObj != null)
                    {
                        builder.RegisterType(type).AsImplementedInterfaces().Named(module.ModuleName, interfaceObj);
                        builder.RegisterType(type).Named(module.ModuleName, type);
                    }
                }
            }
            #endregion
            return(result);
        }
 Mutate <TLimit, TActivatorData, TRegistrationStyle>(
     IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> registration) =>
 registration.EnableInterfaceInterceptors().InterceptedBy(typeof(FooInterceptor));
Beispiel #35
0
 InstancePerHttpRequest <TLimit, TActivatorData, TStyle>(
     this IRegistrationBuilder <TLimit, TActivatorData, TStyle> registration, params object[] lifetimeScopeTags)
 {
     return(registration.InstancePerRequest(lifetimeScopeTags));
 }
        RegisterBusinessModules(this ContainerBuilder builder)
        {
            var referenceAssemblies = builder.GetReferenceAssembly();
            IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> result = null;

            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }
            var repositoryAssemblies = referenceAssemblies.Where(
                p =>
                p.GetCustomAttribute <AssemblyModuleTypeAttribute>().Type == ModuleType.BusinessModule ||
                p.GetCustomAttribute <AssemblyModuleTypeAttribute>().Type == ModuleType.Domain).ToList();

            foreach (var repositoryAssembly in repositoryAssemblies)
            {
                result = builder.RegisterAssemblyTypes(repositoryAssembly).AsImplementedInterfaces().SingleInstance();
            }
            return(result);
        }
 protected virtual void ExtendedHandlerRegisterationDetails(IRegistrationBuilder <object, SimpleActivatorData, SingleRegistrationStyle> registrationBuilder, Type handlerType)
 {
 }
        public static IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> RegisterWcfServices(
            this ContainerBuilder builder)
        {
            var referenceAssemblies = builder.GetReferenceAssembly();
            IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> result = null;

            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }
            var interfaceAssemblies = referenceAssemblies.Where(
                p =>
                p.GetCustomAttribute <AssemblyModuleTypeAttribute>().Type == ModuleType.WcfService).ToList();

            foreach (var interfaceAssembly in interfaceAssemblies)
            {
                result = builder.RegisterAssemblyTypes(interfaceAssembly)
                         .Where(t => t.Name.EndsWith("Service")).SingleInstance();
            }
            return(result);
        }
Beispiel #39
0
 public WebSiteRegistrator(IRegistrationBuilder builder)
 {
     _builder = builder;
 }