/// <summary>
 /// Construct an instance of the <see cref="RegistrationSourceAddedEventArgs"/> class.
 /// </summary>
 /// <param name="componentRegistry">The registry to which the source was added.</param>
 /// <param name="registrationSource">The source that was added.</param>
 /// <exception cref="ArgumentNullException"></exception>
 public RegistrationSourceAddedEventArgs(IComponentRegistry componentRegistry, IRegistrationSource registrationSource)
 {
     if (componentRegistry == null) throw new ArgumentNullException("componentRegistry");
     if (registrationSource == null) throw new ArgumentNullException("registrationSource");
     _componentRegistry = componentRegistry;
     _registrationSource = registrationSource;
 }
Example #2
0
        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
        {
            var implementationType = registration.Activator.LimitType;

            foreach (var autoWireType in autoWireTypes)
            {
                var constructors = implementationType.GetConstructorsWithDependency(autoWireType);

                if (constructors.Any())
                {
                    registration.Preparing += (sender, e) =>
                    {
                        var parameter = new TypedParameter(autoWireType,
                            e.Context.Resolve(autoWireType, new TypedParameter(typeof(Type), implementationType)));
                        e.Parameters = e.Parameters.Concat(new[] { parameter });
                    };
                }
                else
                {
                    var props = implementationType.GetPropertiesWithDependency(autoWireType);
                    if (props.Any())
                    {
                        registration.Activated += (s, e) =>
                        {
                            foreach (var prop in props)
                            {
                                prop.SetValue(e.Instance,
                                    e.Context.Resolve(autoWireType));
                            }
                        };
                    }
                }
            }

            foreach (var serviceType in typebasedServiceTypes)
            {
                var constructorInjectors = BuildConstructorServiceInjectors(implementationType, serviceType).ToArray();
                if (constructorInjectors.Any())
                {
                    registration.Preparing += (s, e) =>
                    {
                        foreach (var ci in constructorInjectors)
                            ci(e);
                    };
                    return;
                }

                // build an array of actions on this type to assign loggers to member properties
                var injectors = BuildPropertyServiceInjectors(implementationType, serviceType).ToArray();

                if (injectors.Any())
                {
                    registration.Activated += (s, e) =>
                    {
                        foreach (var injector in injectors)
                            injector(e.Context, e.Instance);
                    };
                }
            }
        }
Example #3
0
 public CopyOnWriteRegistry(IComponentRegistry readRegistry, Func<IComponentRegistry> createWriteRegistry)
 {
     if (readRegistry == null) throw new ArgumentNullException("readRegistry");
     if (createWriteRegistry == null) throw new ArgumentNullException("createWriteRegistry");
     _readRegistry = readRegistry;
     _createWriteRegistry = createWriteRegistry;
 }
 protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
 {
     registration.Preparing += (sender, args) =>
         {
             args.Parameters = args.Parameters.Union( new[] { new NamedParameter(@"basePoint", _basePoint) } );
         };
 }
Example #5
0
 public void Configure(IComponentRegistry componentRegistry)
 {
     componentRegistry.Registered += (s, e) =>
     {
         e.ComponentRegistration.Preparing += OnComponentPreparing;
     };
 }
        public void Configure(IComponentRegistry componentRegistry)
        {
            var builder = new ContainerBuilder();

            if (_atomicStorageFactory == null)
            {
                AtomicIsInMemory(strategyBuilder => { });
            }
            if (_streamingRoot == null)
            {
                StreamingIsInFiles(Directory.GetCurrentDirectory());
            }
            if (_tapeStorage == null)
            {
                TapeIsInMemory();
            }

            var core = new AtomicRegistrationCore(_atomicStorageFactory);
            var source = new AtomicRegistrationSource(core);
            builder.RegisterSource(source);
            builder.RegisterInstance(new NuclearStorage(_atomicStorageFactory));
            builder
                .Register(
                    c => new AtomicStorageInitialization(new[] {_atomicStorageFactory}, c.Resolve<ISystemObserver>()))
                .As<IEngineProcess>().SingleInstance();

            builder.RegisterInstance(_streamingRoot);

            builder.RegisterInstance(_tapeStorage);
            builder.RegisterInstance(new TapeStorageInitilization(new[] {_tapeStorage})).As<IEngineProcess>();

            builder.Update(componentRegistry);
        }
 protected override void AttachToComponentRegistration(
     IComponentRegistry componentRegistry,
     IComponentRegistration registration)
 {
     registration.Preparing += (sender, args) =>
         log.Debug($@"Resolving concrete type {args.Component.Activator.LimitType}");
 }
 protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
 {
   registration.Preparing += (s, e) =>
   {
     e.Parameters = new [] { loggerParameter }.Concat(e.Parameters);
   };
 }
Example #9
0
 /// <summary>
 /// Create a root lifetime scope for the provided components.
 /// </summary>
 /// <param name="tag">The tag applied to the <see cref="ILifetimeScope"/>.</param>
 /// <param name="componentRegistry">Components used in the scope.</param>
 public LifetimeScope(IComponentRegistry componentRegistry, object tag)
     : this()
 {
     _componentRegistry = Enforce.ArgumentNotNull(componentRegistry, "componentRegistry");
     _root = this;
     _tag = Enforce.ArgumentNotNull(tag, "tag");
 }
    protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
    {
      var type = registration.Activator.LimitType;  //  AF2.0+
      //  .Descriptor.BestKnownImplementationType;  //  AF1.2+

      //  we hook preparing to inject the logger into the constructor
      registration.Preparing += OnComponentPreparing;

      // build the list of actions for type and assign loggers to properties
      var injectors = BuildLogPropertyInjectors(type);

      // no logger properties, no need to hook up the event
// ReSharper disable PossibleMultipleEnumeration
      if (!injectors.Any())
// ReSharper restore PossibleMultipleEnumeration
        return;

      // we hook acticating to inject the logger into the known public properties
      registration.Activating += (s, e) =>
      {
// ReSharper disable PossibleMultipleEnumeration
        foreach (var injector in injectors)
// ReSharper restore PossibleMultipleEnumeration
          injector(e.Context, e.Instance);
      };
    }
		protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry,
			IComponentRegistration registration)
		{
			registration.Preparing += RegistrationOnPreparing;
			registration.Activating += RegistrationOnActivating;
			base.AttachToComponentRegistration(componentRegistry, registration);
		}
        protected override void AttachToRegistrationSource(IComponentRegistry componentRegistry, IRegistrationSource registrationSource)
        {
            base.AttachToRegistrationSource(componentRegistry, registrationSource);

            var message = new RegistrationSourceAddedMessage(_modelMapper.GetRegistrationSourceModel(registrationSource));
            Send(message);
        }
 protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
 {
     registration.Activating += (sender, e) =>
     {
         if (typeof (IMessageConsumer).IsAssignableFrom(e.Instance.GetType()))
             consumerInterceptor.ItemCreated(e.Instance.GetType(), e.Component.Lifetime.GetType().Equals(typeof(CurrentScopeLifetime)));
     };
 }
		protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
		{
			registration.Preparing += (sender, args) => args.Parameters = args.Parameters.Concat(new[]
			{
				new ResolvedParameter((info, context) => info.ParameterType == typeof (ILog),
					(info, context) => _logFactory(info.Member.DeclaringType))
			});
		}
        /// <summary>
        /// Construct an instance of the <see cref="RegistrationSourceAddedEventArgs"/> class.
        /// </summary>
        /// <param name="componentRegistry">The registry to which the source was added.</param>
        /// <param name="registrationSource">The source that was added.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public RegistrationSourceAddedEventArgs(IComponentRegistry componentRegistry, IRegistrationSource registrationSource)
        {
            if (componentRegistry == null) throw new ArgumentNullException(nameof(componentRegistry));
            if (registrationSource == null) throw new ArgumentNullException(nameof(registrationSource));

            ComponentRegistry = componentRegistry;
            RegistrationSource = registrationSource;
        }
 protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
 {
     Type implementationType = registration.Activator.LimitType;
     if (DynamicProxyContext.From(registration) != null && implementationType.FullName == "Orchard.Car.Services.CarInfoService")
     {
         registration.InterceptedBy<SimpleInterceptor>();
     }
 }
        public void Configure(IComponentRegistry componentRegistry)
        {
            // This is necessary as generic dependencies are currently not resolved, see issue: http://orchard.codeplex.com/workitem/18141
            var builder = new ContainerBuilder();
            builder.RegisterGeneric(typeof(Resolve<>)).As(typeof(IResolve<>));

            builder.Update(componentRegistry);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ComponentRegisteredEventArgs"/> class.
        /// </summary>
        /// <param name="registry">The container into which the registration
        /// was made.</param>
        /// <param name="componentRegistration">The component registration.</param>
        public ComponentRegisteredEventArgs(IComponentRegistry registry, IComponentRegistration componentRegistration)
        {
            if (registry == null) throw new ArgumentNullException(nameof(registry));
            if (componentRegistration == null) throw new ArgumentNullException(nameof(componentRegistration));

            ComponentRegistry = registry;
            ComponentRegistration = componentRegistration;
        }
Example #19
0
        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
        {
            // Handle constructor parameters.
            registration.Preparing += OnComponentPreparing;

            // Handle properties.
            registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
        }
 protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
 {
     // Use the event args to log detailed info
     registration.Preparing += (sender, args) =>                      
         Debug.WriteLine(
             "Resolving concrete type {0}, Id {1}",
             args.Component.Activator.LimitType, args.Component.Id.ToString());
 }
Example #21
0
        /// <summary>
        /// Create a lifetime scope for the provided components and nested beneath a parent.
        /// </summary>
        /// <param name="tag">The tag applied to the <see cref="ILifetimeScope"/>.</param>
        /// <param name="componentRegistry">Components used in the scope.</param>
        /// <param name="parent">Parent scope.</param>
        protected LifetimeScope(IComponentRegistry componentRegistry, LifetimeScope parent, object tag)
            : this(componentRegistry, tag)
        {
            if (parent == null) throw new ArgumentNullException(nameof(parent));

            _parent = parent;
            RootLifetimeScope = _parent.RootLifetimeScope;
        }
 /// <summary>
 /// Override to attach module-specific functionality to a
 /// component registration.
 /// </summary>
 /// <remarks>This method will be called for all existing <i>and future</i> component
 /// registrations - ordering is not important.</remarks>
 /// <param name="componentRegistry">The component registry.</param>
 /// <param name="registration">The registration to attach functionality to.</param>
 protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
 {
     if (registration == null)
     {
         throw new ArgumentNullException("registration");
     }
     foreach (var property in MetadataHelper.GetMetadata(registration.Activator.LimitType))
         registration.Metadata.Add(property);
 }
Example #23
0
        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
        {
            base.AttachToComponentRegistration(componentRegistry, registration);

            if (registration.Activator.LimitType.IsAssignableTo<IHandle>())
            {
                registration.Activated += RegistrationOnActivated;
            }
        }
Example #24
0
 /// <summary>
 /// Apply the module to the component registry.
 /// </summary>
 /// <param name="componentRegistry">Component registry to apply configuration to.</param>
 public void Configure(IComponentRegistry componentRegistry)
 {
     if (componentRegistry == null) throw new ArgumentNullException("componentRegistry");
     var moduleBuilder = new ContainerBuilder();
     Load(moduleBuilder);
     moduleBuilder.Update(componentRegistry);
     AttachToRegistrations(componentRegistry);
     AttachToSources(componentRegistry);
 }
Example #25
0
        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
        {
            var implementationType = registration.Activator.LimitType;
            var property = FindProperty(implementationType);

            if (property != null) {
                registration.InterceptedBy<ISecurityModuleInterceptor>();
            }
        }
Example #26
0
        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) {

            if (!registration.Services.Contains(new TypedService(typeof(ICommandHandler))))
                return;

            var builder = new CommandHandlerDescriptorBuilder();
            var descriptor = builder.Build(registration.Activator.LimitType);
            registration.Metadata.Add(typeof(CommandHandlerDescriptor).FullName, descriptor);
        }
        void IModule.Configure(IComponentRegistry componentRegistry)
        {
            ApplyProxyFactory(_config);
            _builder.RegisterInstance(_config.BuildSessionFactory());

            // Session is created for the entire message batch
            _builder.Register(ComposeSession)
                .InstancePerMatchingLifetimeScope(DispatchLifetimeScopeTags.MessageEnvelopeScopeTag);
            _builder.Update(componentRegistry);
        }
        /// <summary>
        ///     Apply the module to the component registry.
        /// </summary>
        /// <param name = "componentRegistry">
        ///     Component registry to apply configuration to.
        /// </param>
        public void Configure(IComponentRegistry componentRegistry)
        {
            foreach (var registration in componentRegistry.Registrations)
            {
                this.AttachToComponentRegistration(registration);
            }

            componentRegistry.Registered +=
                (sender, e) => this.AttachToComponentRegistration(e.ComponentRegistration);
        }
Example #29
0
        /// <summary>
        /// Create a root lifetime scope for the provided components.
        /// </summary>
        /// <param name="tag">The tag applied to the <see cref="ILifetimeScope"/>.</param>
        /// <param name="componentRegistry">Components used in the scope.</param>
        public LifetimeScope(IComponentRegistry componentRegistry, object tag)
            : this()
        {
            if (componentRegistry == null) throw new ArgumentNullException(nameof(componentRegistry));
            if (tag == null) throw new ArgumentNullException(nameof(tag));

            ComponentRegistry = componentRegistry;
            RootLifetimeScope = this;
            Tag = tag;
        }
        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
        {
            base.AttachToComponentRegistration(componentRegistry, registration);

            var includedTypes = _modelMapper.GetReferencedTypes(registration);
            foreach (var includedType in includedTypes)
                SendTypeModelIfNeeded(includedType);
           var message = new ComponentAddedMessage(_modelMapper.GetComponentModel(registration));            
            Send(message);
        }
        public static void RegisterEventStoreStorage(this IComponentRegistry registry)
        {
            Guard.AgainstNull(registry, nameof(registry));

            registry.AttemptRegister <IScriptProviderConfiguration, ScriptProviderConfiguration>();
            registry.AttemptRegister <IScriptProvider, ScriptProvider>();

            registry.AttemptRegister <IConcurrencyExceptionSpecification, ConcurrencyExceptionSpecification>();

            registry.AttemptRegister <IDatabaseContextCache, ThreadStaticDatabaseContextCache>();
            registry.AttemptRegister <IDatabaseContextFactory, DatabaseContextFactory>();
            registry.AttemptRegister <IDbConnectionFactory, DbConnectionFactory>();
            registry.AttemptRegister <IDbCommandFactory, DbCommandFactory>();
            registry.AttemptRegister <IDatabaseGateway, DatabaseGateway>();
            registry.AttemptRegister <IQueryMapper, QueryMapper>();
            registry.AttemptRegister <IPrimitiveEventRepository, PrimitiveEventRepository>();
            registry.AttemptRegister <IPrimitiveEventQueryFactory, PrimitiveEventQueryFactory>();
            registry.AttemptRegister <IKeyStoreQueryFactory, KeyStoreQueryFactory>();
            registry.AttemptRegister <IKeyStore, KeyStore>();
            registry.AttemptRegister <IEventTypeStore, EventTypeStore>();
            registry.AttemptRegister <IEventTypeStoreQueryFactory, EventTypeStoreQueryFactory>();
        }
Example #32
0
        protected override void RegisterComponents(IComponentRegistry registry, IDataFacility facility)
        {
            registry.Register <IDbContextDataProvider <TDbContext> >()
            .Add <DbContextDataProvider <TTag, TDbContext> >()
            .PerScope()
            .IfNoneRegistered();

            registry.Register <IDataProvider>()
            .Add(c => c.Resolve <IDbContextDataProvider <TDbContext> >())
            .PerScope()
            .IfNotRegistered();

            registry.Register <ITransactionManager>()
            .Add(c => c.Resolve <IDbContextDataProvider <TDbContext> >().TransactionManager)
            .PerScope()
            .IfNotRegistered();

            foreach (Action <IComponentRegistry, IDataFacility> registrationCallback in _registrationCallbacks)
            {
                registrationCallback(registry, facility);
            }
        }
Example #33
0
 protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
 {
     base.AttachToComponentRegistration(componentRegistry, registration);
     registration.Activated += (sender, args) =>
     {
         if (args == null)
         {
             return;
         }
         foreach (var i in args.Instance.GetType().GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IHandle <>)))
         {
             var messageType = i.GetGenericArguments().FirstOrDefault();
             var method      = i.GetMethod("Handle", new[] { messageType });
             if (messageType != null)
             {
                 args.Context.Resolve <IMessageAggregator>()
                 .Messages.Where(m => m.GetType() == messageType)
                 .Subscribe(m => method.Invoke(args.Instance, new object[] { m }));
             }
         }
     };
 }
Example #34
0
        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
        {
            var implementationType = registration.Activator.LimitType;

            // build an array of actions on this type to assign loggers to member properties
            var injectors = BuildLoggerInjectors(implementationType).ToArray();

            // if there are no logger properties, there's no reason to hook the activated event
            if (!injectors.Any())
            {
                return;
            }

            // otherwise, whan an instance of this component is activated, inject the loggers on the instance
            registration.Activated += (s, e) =>
            {
                foreach (var injector in injectors)
                {
                    injector(e.Context, e.Instance);
                }
            };
        }
Example #35
0
        public static CodeLensFeature Create(
            IComponentRegistry components,
            EditorSession editorSession)
        {
            var codeLenses =
                new CodeLensFeature(
                    editorSession,
                    components.Get <IMessageHandlers>(),
                    components.Get <ILogger>());

            codeLenses.Providers.Add(
                new ReferencesCodeLensProvider(
                    editorSession));

            codeLenses.Providers.Add(
                new PesterCodeLensProvider(
                    editorSession));

            editorSession.Components.Register <ICodeLenses>(codeLenses);

            return(codeLenses);
        }
Example #36
0
        public void WhenContainerIsBuilt_OnRegisteredHandlersAreInvoked()
        {
            var builder = new ContainerBuilder();

            var marker = "marker";

            IComponentRegistry     registry = null;
            IComponentRegistration cr       = null;

            builder.RegisterType <object>()
            .WithMetadata(marker, marker)
            .OnRegistered(e =>
            {
                registry = e.ComponentRegistry;
                cr       = e.ComponentRegistration;
            });

            var container = builder.Build();

            Assert.Same(container.ComponentRegistry, registry);
            Assert.Same(marker, cr.Metadata[marker]);
        }
        static void ScanAssemblies(IEnumerable <Assembly> assemblies, IComponentRegistry cr, IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> rb)
        {
            rb.ActivatorData.Filters.Add(t =>
                                         rb.RegistrationData.Services.OfType <IServiceWithType>().All(swt =>
                                                                                                      swt.ServiceType.IsAssignableFrom(t)));

            foreach (var t in assemblies
                     .SelectMany(a => a.GetTypes())
                     .Where(t =>
                            t.IsClass &&
                            !t.IsAbstract &&
                            !t.IsGenericTypeDefinition &&
                            !t.IsDelegate() &&
                            rb.ActivatorData.Filters.All(p => p(t))))
            {
                var scanned = RegistrationBuilder.ForType(t)
                              .FindConstructorsWith(rb.ActivatorData.ConstructorFinder)
                              .UsingConstructor(rb.ActivatorData.ConstructorSelector)
                              .WithParameters(rb.ActivatorData.ConfiguredParameters)
                              .WithProperties(rb.ActivatorData.ConfiguredProperties);

                scanned.RegistrationData.CopyFrom(rb.RegistrationData, false);

                foreach (var action in rb.ActivatorData.ConfigurationActions)
                {
                    action(t, scanned);
                }

                if (scanned.RegistrationData.Services.Any())
                {
                    RegistrationBuilder.RegisterSingleComponent(cr, scanned);
                }
            }

            foreach (var postScanningCallback in rb.ActivatorData.PostScanningCallbacks)
            {
                postScanningCallback(cr);
            }
        }
 protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
 {
     base.AttachToComponentRegistration(componentRegistry, registration);
     if (registration.Activator.LimitType == typeof(TService))
     {
         registration.Preparing += (sender, e) =>
         {
             e.Parameters = e.Parameters.Union(
                 new[]
             {
                 new ResolvedParameter(
                     (p, i) => p.ParameterType == typeof(HttpClient),
                     (p, i) => {
                     HttpClient client = i.Resolve <IHttpClientFactory>().CreateClient();
                     this._clientConfigurator(client);
                     return(client);
                 }
                     )
             });
         };
     }
 }
Example #39
0
        /// <summary>
        /// Register a component in the component registry. This helper method is necessary
        /// in order to execute OnRegistered hooks and respect PreserveDefaults.
        /// </summary>
        /// <remarks>Hoping to refactor this out.</remarks>
        /// <param name="cr">Component registry to make registration in.</param>
        /// <param name="builder">Registration builder with data for new registration.</param>
        public static void RegisterSingleComponent <TLimit, TActivatorData, TSingleRegistrationStyle>(
            IComponentRegistry cr,
            IRegistrationBuilder <TLimit, TActivatorData, TSingleRegistrationStyle> builder)
            where TSingleRegistrationStyle : SingleRegistrationStyle
            where TActivatorData : IConcreteActivatorData
        {
            if (cr == null)
            {
                throw new ArgumentNullException(nameof(cr));
            }

            var registration = CreateRegistration(builder);

            cr.Register(registration, builder.RegistrationStyle.PreserveDefaults);

            var registeredEventArgs = new ComponentRegisteredEventArgs(cr, registration);

            foreach (var rh in builder.RegistrationStyle.RegisteredHandlers)
            {
                rh(cr, registeredEventArgs);
            }
        }
        /// <summary>
        ///     Creates an instance of all types implementing the `IComponentRegistryBootstrap` interface and calls the `Register`
        ///     method.
        /// </summary>
        /// <param name="registry">The `IComponentRegistry` instance to pass register the components in.</param>
        /// <param name="registryConfiguration">The `IComponentRegistryConfiguration` instance that contains the registry configuration.</param>
        /// <param name="bootstrapConfiguration">The `IBootstrapConfiguration` instance that contains the bootstrapping configuration.</param>
        public static void RegistryBoostrap(this IComponentRegistry registry,
                                            IComponentRegistryConfiguration registryConfiguration, IBootstrapConfiguration bootstrapConfiguration)
        {
            Guard.AgainstNull(registry, "registry");

            var completed = new List <Type>();

            var reflectionService = new ReflectionService();

            foreach (var assembly in bootstrapConfiguration.Assemblies)
            {
                foreach (var type in reflectionService.GetTypes <IComponentRegistryBootstrap>(assembly))
                {
                    if (completed.Contains(type))
                    {
                        continue;
                    }

                    type.AssertDefaultConstructor(string.Format(InfrastructureResources.DefaultConstructorRequired,
                                                                "IComponentRegistryBootstrap", type.FullName));

                    ((IComponentRegistryBootstrap)Activator.CreateInstance(type)).Register(registry);

                    completed.Add(type);
                }
            }

            foreach (var component in registryConfiguration.Components)
            {
                registry.Register(component.DependencyType, component.ImplementationType, component.Lifestyle);
            }

            foreach (var collection in registryConfiguration.Collections)
            {
                registry.RegisterCollection(collection.DependencyType, collection.ImplementationTypes,
                                            collection.Lifestyle);
            }
        }
Example #41
0
#pragma warning restore CA2213

        public void Init(IPluginInterface pluginInterface, IComponentRegistry componentRegistry)
        {
            this.pluginInterface  = pluginInterface;
            Style.PluginInterface = pluginInterface;

            if (!GdiAvailabilityTest.Test())
            {
                pluginInterface.Logger.Error(T._("Die Bibliothek libgdiplus wurde nicht gefunden! Die Bildfahrplanfunktionen stehen nicht zur Verfügung. Zur Installation siehe Installatiosnhinweise unter https://fahrplan.manuelhu.de/download/."));
                return;
            }

            dpf = new DynamicPreview();
            componentRegistry.Register <IPreviewAction>(dpf);
            pluginInterface.AppClosing += (s, e) => dpf.Close();

#if !DEBUG
            if (pluginInterface.Settings.Get <bool>("feature.enable-full-graph-editor"))
            {
#endif
            pluginInterface.FileStateChanged += PluginInterface_FileStateChanged;

            graphItem = ((MenuBar)pluginInterface.Menu).CreateItem(T._("B&ildfahrplan"));

            showItem = graphItem.CreateItem(T._("&Anzeigen"), enabled: false, clickHandler: ShowItem_Click);
            graphItem.Items.Add(new SeparatorMenuItem());
            printItem  = graphItem.CreateItem(T._("&Drucken"), enabled: false, clickHandler: PrintItem_Click);
            exportItem = graphItem.CreateItem(T._("&Exportieren"), enabled: false, clickHandler: ExportItem_Click);
            graphItem.Items.Add(new SeparatorMenuItem());
            configItem        = graphItem.CreateItem(T._("Darste&llung ändern"), enabled: false, clickHandler: (s, ev) => ShowForm(new ConfigForm(pluginInterface.Timetable, pluginInterface)));
            virtualRoutesItem = graphItem.CreateItem(T._("&Virtuelle Strecken"), enabled: false, clickHandler: (s, ev) => ShowForm(new VirtualRouteForm(pluginInterface)));
            trainColorItem    = graphItem.CreateItem(T._("&Zugdarstellung ändern"), enabled: false, clickHandler: (s, ev) => ShowForm(new TrainStyleForm(pluginInterface)));
            stationStyleItem  = graphItem.CreateItem(T._("&Stationsdarstellung ändern"), enabled: false, clickHandler: (s, ev) => ShowForm(new StationStyleForm(pluginInterface)));
            overrideItem      = graphItem.CreateCheckItem(T._("Verwende nur &Plandarstellung"), isChecked: pluginInterface.Settings.Get <bool>("bifpl.override-entity-styles"),
                                                          changeHandler: OverrideItem_CheckedChanged);
#if !DEBUG
        }
#endif
        }
Example #42
0
        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
        {
            registration.Preparing += (sender, args) =>
            {
                bool Match(ParameterInfo info, IComponentContext context)
                {
                    return(typeof(Microsoft.Extensions.Logging.ILogger).IsAssignableFrom(info.ParameterType));
                }

                object Provide(ParameterInfo info, IComponentContext context)
                {
                    Type            loggerType  = typeof(XUnitLogger <>).MakeGenericType(info.Member.DeclaringType);
                    ConstructorInfo constructor = loggerType.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(ILogger) }, null);

                    Debug.Assert(constructor != null);
                    object instance = constructor.Invoke(new object[] { this.logger.ForContext(info.Member.DeclaringType) });

                    return(instance);
                }

                args.Parameters = args.Parameters.Union(new[] { new ResolvedParameter(Match, Provide) });
            };
        }
Example #43
0
        public static IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> RegisterOwinApplicationContainer(this ContainerBuilder builder)
        {
            return(builder.Register(ctx =>
            {
                ILifetimeScope scope = ctx.Resolve <ILifetimeScope>().BeginLifetimeScope();
                IComponentRegistry registry = scope.ComponentRegistry;
                ContainerBuilder newBuilder = new ContainerBuilder();
                newBuilder.Register(c => new RuntimeRegistrationDelegate(func =>
                {
                    Tuple <Type, object> registerResult = func(scope as IServiceProvider);
                    ContainerBuilder innerNewBuilder = new ContainerBuilder();
                    innerNewBuilder.Register(_ => registerResult.Item2)
                    .As(registerResult.Item1)
                    .ExternallyOwned();

                    innerNewBuilder.Update(registry);
                })).As <RuntimeRegistrationDelegate>().InstancePerLifetimeScope();

                newBuilder.Update(registry);

                return scope as IServiceProvider;
            }).As <IServiceProvider>() as IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle>);
        }
Example #44
0
        /// <summary>
        /// Releases all managed resources.
        /// </summary>
        /// <param name="calledFromFinalizer">Specifies if this method is called from finalizer or not</param>
        private void Dispose(bool calledFromFinalizer)
        {
            if (!_disposed)
            {
                _disposed = true;

                if (_componentRegistry != null)
                {
                    foreach (ComponentRegistration regEntry in _componentRegistry.GetRegistrations())
                    {
                        CleanUpComponentInstance(regEntry);
                    }

                    _componentRegistry.Clear();
                    _componentRegistry = null;
                }

                if (!calledFromFinalizer)
                {
                    GC.SuppressFinalize(this);
                }
            }
        }
Example #45
0
        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry,
                                                              IComponentRegistration registration)
        {
            var implementationType = registration.Activator.LimitType;

            // 根据此类型构建一个actions数组用于把logger赋值给成员属性
            var injectors = BuildLoggerInjectors(implementationType).ToArray();

            // 如果没有logger属性,就没有需要活动事件钩子的理由
            if (!injectors.Any())
            {
                return;
            }

            // 否则,如果激活一个该组件的实例,则在实例上注入loggers
            registration.Activated += (s, e) =>
            {
                foreach (var injector in injectors)
                {
                    injector(e.Context, e.Instance);
                }
            };
        }
Example #46
0
        public override void Update(GameTime gameTime)
        {
            // Get running worlds.
            IReadOnlyList <IWorld> worlds = worldManager.GetWorldsInState(WorldState.Running);

            // Iterate through worlds.
            foreach (IWorld world in worlds)
            {
                // Check if the world has the sprite font component.
                if (!world.ComponentManager.ContainsRegistry <TextRenderComponent>())
                {
                    continue;
                }

                // Get component registries.
                IComponentRegistry <PositionComponent> positionComponents =
                    (IComponentRegistry <PositionComponent>)world.ComponentManager.GetRegistry <PositionComponent>();
                IComponentRegistry <TextRenderComponent> spriteFontComponents =
                    (IComponentRegistry <TextRenderComponent>)world.ComponentManager.GetRegistry <TextRenderComponent>();

                // Begin sprite batch.
                spriteBatch.Begin();

                // Iterate through sprite font components and render.
                foreach (TextRenderComponent component in spriteFontComponents)
                {
                    // Get position.
                    PositionComponent position = positionComponents.Get(component.EntityID);

                    // Render text.
                    spriteBatch.DrawString(component.Font, component.Text, new Vector2(position.X, position.Y), component.Colour);
                }

                // End sprite batch.
                spriteBatch.End();
            }
        }
Example #47
0
        public override void Update(GameTime gameTime)
        {
            // Check if there events to process.
            if (scoreEvents.Count == 0)
            {
                return;
            }

            // Get HUD world.
            IWorld world = worldManager.GetWorld((int)WorldID.HudWorld);

            // Get text render component registry.
            IComponentRegistry <TextRenderComponent> textRenders =
                (IComponentRegistry <TextRenderComponent>)world.ComponentManager.GetRegistry <TextRenderComponent>();

            foreach (ScoreEvent score in scoreEvents)
            {
                // Update score and text.
                if (score.Player == 1)
                {
                    player1Score += score.Amount;
                    TextRenderComponent component = textRenders.Get(player1Text);
                    component.Text = player1Score.ToString();
                    textRenders.Set(component);
                }
                else
                {
                    player2Score += score.Amount;
                    TextRenderComponent component = textRenders.Get(player2Text);
                    component.Text = player2Score.ToString();
                    textRenders.Set(component);
                }
            }

            // Clear list.
            scoreEvents.Clear();
        }
Example #48
0
        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
        {
            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            var  baseType = typeof(WebApiEntityController <,>);
            var  type     = registration.Activator.LimitType;
            Type implementingType;

            if (!type.IsSubClass(baseType, out implementingType))
            {
                return;
            }

            var repoProperty    = FindRepositoryProperty(type, implementingType.GetGenericArguments()[0]);
            var serviceProperty = FindServiceProperty(type, implementingType.GetGenericArguments()[1]);

            if (repoProperty != null || serviceProperty != null)
            {
                registration.Activated += (sender, e) =>
                {
                    if (repoProperty != null)
                    {
                        var repo = e.Context.Resolve(repoProperty.PropertyType);
                        repoProperty.SetValue(e.Instance, repo, null);
                    }

                    if (serviceProperty != null)
                    {
                        var service = e.Context.Resolve(serviceProperty.PropertyType);
                        serviceProperty.SetValue(e.Instance, service, null);
                    }
                };
            }
        }
        public static DocumentSymbolFeature Create(
            IComponentRegistry components,
            EditorSession editorSession)
        {
            var documentSymbols =
                new DocumentSymbolFeature(
                    editorSession,
                    components.Get <IMessageHandlers>(),
                    components.Get <ILogger>());

            documentSymbols.Providers.Add(
                new ScriptDocumentSymbolProvider(
                    editorSession.PowerShellContext.LocalPowerShellVersion.Version));

            documentSymbols.Providers.Add(
                new PsdDocumentSymbolProvider());

            documentSymbols.Providers.Add(
                new PesterDocumentSymbolProvider());

            editorSession.Components.Register <IDocumentSymbols>(documentSymbols);

            return(documentSymbols);
        }
Example #50
0
        public void Init(IPluginInterface pluginInterface, IComponentRegistry componentRegistry)
        {
            this.pluginInterface = pluginInterface;

            if (pluginInterface.Settings.Get <bool>("dump.record"))
            {
                var defaultPath = pluginInterface.GetTemp("..");
                var basePath    = pluginInterface.Settings.Get("dump.path", defaultPath);
                if (basePath == "")
                {
                    basePath = defaultPath;
                }
                basePath = Path.GetFullPath(basePath);
                if (!Directory.Exists(basePath))
                {
                    Directory.CreateDirectory(basePath);
                }

                listener = new DebugListener();
                listener.StartSession(pluginInterface, basePath);
            }

            pluginInterface.ExtensionsLoaded += PluginInterfaceOnExtensionsLoaded;
        }
Example #51
0
        public static void RegisterEventProcessing(this IComponentRegistry registry)
        {
            Guard.AgainstNull(registry, nameof(registry));

            if (!registry.IsRegistered <IProjectionConfiguration>())
            {
                registry.AttemptRegisterInstance <IProjectionConfiguration>(ProjectionSection.Configuration(new ConnectionConfigurationProvider()));
            }

            registry.AttemptRegister <IScriptProviderConfiguration, ScriptProviderConfiguration>();
            registry.AttemptRegister <IScriptProvider, ScriptProvider>();

            registry.AttemptRegister <IDatabaseContextCache, ThreadStaticDatabaseContextCache>();
            registry.AttemptRegister <IDatabaseContextFactory, DatabaseContextFactory>();
            registry.AttemptRegister <IDbConnectionFactory, DbConnectionFactory>();
            registry.AttemptRegister <IDbCommandFactory, DbCommandFactory>();
            registry.AttemptRegister <IDatabaseGateway, DatabaseGateway>();
            registry.AttemptRegister <IQueryMapper, QueryMapper>();
            registry.AttemptRegister <IProjectionRepository, ProjectionRepository>();
            registry.AttemptRegister <IProjectionQueryFactory, ProjectionQueryFactory>();

            registry.AttemptRegister <EventProcessingObserver, EventProcessingObserver>();
            registry.AttemptRegister <EventProcessingModule, EventProcessingModule>();
        }
Example #52
0
        protected void Boostrap(IComponentRegistry registry)
        {
            registry.RegisterInstance <ITransactionScopeFactory>(new DefaultTransactionScopeFactory(false, IsolationLevel.Unspecified, TimeSpan.Zero));

#if (NETCOREAPP2_1 || NETSTANDARD2_0)
            DbProviderFactories.RegisterFactory("System.Data.SqlClient", System.Data.SqlClient.SqlClientFactory.Instance);

            var connectionConfigurationProvider = new Mock <IConnectionConfigurationProvider>();

            connectionConfigurationProvider.Setup(m => m.Get(It.IsAny <string>())).Returns(
                (string name) =>
                name.Equals("EventStoreProjection")
                        ? new ConnectionConfiguration(
                    "EventStoreProjection",
                    "System.Data.SqlClient",
                    "Data Source=.\\sqlexpress;Initial Catalog=ShuttleProjection;Integrated Security=SSPI;")
                        : new ConnectionConfiguration(
                    name,
                    "System.Data.SqlClient",
                    "Data Source=.\\sqlexpress;Initial Catalog=Shuttle;Integrated Security=SSPI;"));

            registry.AttemptRegisterInstance(connectionConfigurationProvider.Object);

            registry.RegisterInstance <IProjectionConfiguration>(new ProjectionConfiguration
            {
                EventProjectionConnectionString =
                    connectionConfigurationProvider.Object.Get("EventStoreProjection").ConnectionString,
                EventProjectionProviderName =
                    connectionConfigurationProvider.Object.Get("EventStoreProjection").ProviderName,
                EventStoreConnectionString = connectionConfigurationProvider.Object.Get("Shuttle").ConnectionString,
                EventStoreProviderName     = connectionConfigurationProvider.Object.Get("Shuttle").ProviderName
            });
#else
            registry.AttemptRegister <IConnectionConfigurationProvider, ConnectionConfigurationProvider>();
#endif
        }
        private void Build(IComponentRegistry componentRegistry, bool excludeDefaultModules)
        {
            if (componentRegistry == null)
            {
                throw new ArgumentNullException(nameof(componentRegistry));
            }

            if (_wasBuilt)
            {
                throw new InvalidOperationException(ContainerBuilderResources.BuildCanOnlyBeCalledOnce);
            }

            _wasBuilt = true;

            if (!excludeDefaultModules)
            {
                RegisterDefaultAdapters(componentRegistry);
            }

            foreach (var callback in _configurationCallbacks)
            {
                callback(componentRegistry);
            }
        }
Example #54
0
 /// <summary>
 /// Create a lifetime scope for the provided components and nested beneath a parent.
 /// </summary>
 /// <param name="tag">The tag applied to the <see cref="ILifetimeScope"/>.</param>
 /// <param name="componentRegistry">Components used in the scope.</param>
 /// <param name="parent">Parent scope.</param>
 protected LifetimeScope(IComponentRegistry componentRegistry, LifetimeScope parent, object tag)
     : this(componentRegistry, tag)
 {
     _parent = Enforce.ArgumentNotNull(parent, "parent");
     _root   = _parent.RootLifetimeScope;
 }
Example #55
0
 /// <summary>
 /// Create a root lifetime scope for the provided components.
 /// </summary>
 /// <param name="componentRegistry">Components used in the scope.</param>
 public LifetimeScope(IComponentRegistry componentRegistry)
     : this(componentRegistry, RootTag)
 {
 }
Example #56
0
 protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry,
                                                       IComponentRegistration registration)
 {
     registration.Activated += GetTempDataFromMvcControllers;
 }
 public static IComponentRegistration GetRegistration <T>(this IComponentRegistry registry)
 {
     return(GetRegistration(registry, typeof(T)));
 }
Example #58
0
 protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry,
                                                       IComponentRegistration registration)
 {
     registration.Preparing += OnComponentPreparing;
 }
Example #59
0
 protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
 {
     registration.Preparing += ConfigureLoggerParameter;
 }
 public ComponentRegisteredEventArgs(IComponentRegistry registry, IComponentRegistration componentRegistration)
 {
     this._componentRegistry     = Enforce.ArgumentNotNull <IComponentRegistry>(registry, "registry");
     this._componentRegistration = Enforce.ArgumentNotNull <IComponentRegistration>(componentRegistration, "componentRegistration");
 }