protected override void Init()
        {
            ComponentRegistration <object> component = Component.For(typeof(IRepository <>)).ImplementedBy(typeof(NHRepository <>));

            if (!string.IsNullOrEmpty(config.RepositoryKey))
            {
                component.Named(config.RepositoryKey);
            }

            Kernel.Register(component);
            ComponentRegistration <IUnitOfWorkFactory> registerFactory =
                Component.For <IUnitOfWorkFactory>()
                .ImplementedBy <NHibernateUnitOfWorkFactory>();

            registerFactory.Parameters(ComponentParameter.ForKey("configurationFileName").Eq(config.NHibernateConfigurationFile));

            // if we are running in test mode, we don't want to register
            // the assemblies directly, we let the DatabaseTestFixtureBase do it
            // this allow us to share the configuration between the test & prod projects
            if (DatabaseTestFixtureBase.IsRunningInTestMode == false)
            {
                registerFactory.DependsOn(Property.ForKey("assemblies").Eq(Assemblies));
            }
            Kernel.Register(registerFactory);

            Kernel.AddComponentInstance("entitiesToRepositories", typeof(INHibernateInitializationAware),
                                        new EntitiesToRepositoriesInitializationAware(config.IsCandidateForRepository));
        }
예제 #2
0
        protected override void Init()
        {
            Kernel.ComponentRegistered += Kernel_ComponentRegistered;

            _runtime = new WorkflowRuntime();
            Kernel.AddComponentInstance("workflowruntime", _runtime);
        }
        private void ConfigureFactories(IConfiguration config)
        {
            String id = config.Attributes["id"];

            if (id == null || String.Empty.Equals(id))
            {
                throw new System.Configuration.ConfigurationException("You must provide a valid 'id' attribute for the 'factory' node");
            }

            Configuration cfg = new Configuration();

            ApplyConfigurationSettings(cfg, config.Children["settings"]);
            RegisterAssemblies(cfg, config.Children["assemblies"]);
            RegisterResources(cfg, config.Children["resources"]);

            // Registers the Configuration object

            Kernel.AddComponentInstance(String.Format("{0}.cfg", id), cfg);

            // Registers the ISessionFactory with a custom activator

            ComponentModel model = new ComponentModel(id, typeof(ISessionFactory), null);

            model.ExtendedProperties.Add(ConfiguredObject, cfg);
            model.LifestyleType            = LifestyleType.Singleton;
            model.CustomComponentActivator = typeof(SessionFactoryActivator);
            Kernel.AddCustomComponent(model);
        }
        private void RegisterAdapterWithKernel()
        {
            String adapterName = String.Format("#ContainerAdapter:{0}#", Guid.NewGuid());

            Kernel.AddComponentInstance(adapterName, this);

            Kernel.ComponentUnregistered += new ComponentDataDelegate(OnComponentUnregistered);
        }
        private void CreateSnapshotTaker(PrevalenceEngine engine, float snapshotPeriod)
        {
            TimeSpan       period = TimeSpan.FromHours(snapshotPeriod);
            ICleanUpPolicy policy = (ICleanUpPolicy)Kernel[PrevalenceFacility.CleanupPolicyComponentPropertyKey];

            SnapshotTaker taker = new SnapshotTaker(engine, period, policy);

            Kernel.AddComponentInstance(PrevalenceFacility.SnapShotTakerComponentPropertyKey, taker);
        }
        private void Initialize(HttpApplication app)
        {
            Kernel.AddComponentInstance("this", typeof(IWindsorContainer), this);

            if (app != null)
            {
                Kernel.AddComponentInstance("web.app", typeof(HttpApplication), app);
            }

            Initialize();
        }
예제 #7
0
        public void InitializeContainer(IApplicationContext context, PredefinedService[] predefinedServices)
        {
            ((DefaultKernel)Kernel).ComponentModelBuilder = new ComponentModelBuilder(Kernel);

            Kernel.ReleasePolicy = new ExplicitReleasePolicy();


            Connect(RuntimeConstants.MiniKernelId, this, typeof(IKernel));

            Connect("kernel", Kernel, typeof(IKernel));
            Connect("windsorContainer", this, typeof(IWindsorContainer));

            //AddCustomComponents(context);
            Kernel.AddComponentInstance(RuntimeConstants.RuntimeConfigurationId, typeof(IApplicationContext), context);


            if (KernelLogger.IsDebugEnabled)
            {
                new KernelLogger(Kernel);
            }

            Kernel.AddComponentInstance(RuntimeConstants.ProductId, typeof(IApplicationContext), context);


            //AddCustomFacilities();
            AddFacility(ComponentIdAwareFacilityId,
                        new TypeAwareFacility(ComponentIdAwareConcern.ComponentIdAwareModelPropertyName, typeof(IComponentIdAware),
                                              ComponentIdAwareConcern.Instance));
            AddFacility(ServiceRunnerFacility.ComponentTypeId, new ServiceRunnerFacility());
            AddFacility(ComponentFacility.ComponentTypeId, new ComponentFacility());


            if (null != context.Arguments)
            {
                Connect(RuntimeConstants.ParsedCommandLineArgumentsId, context.Arguments, typeof(ICommandLineArguments));
            }



            _logger.Debug(" + 开始添加预定义的服务...");

            foreach (PredefinedService svc in predefinedServices)
            {
                Kernel.AddComponent(svc.Id, svc.Service, svc.Implementation);
            }

            _logger.Debug(" > 添加预定义的服务完成.");


            //_initializing = false;
            //_initialized = true;
        }
예제 #8
0
        protected override void Init()
        {
            Kernel.Register(Component.For(typeof(IRepository <>)).ImplementedBy(typeof(NHRepository <>)));

            MultipleNHibernateUnitOfWorkFactory unitOfWorkFactory = new MultipleNHibernateUnitOfWorkFactory();

            foreach (NHibernateUnitOfWorkFacilityConfig config in configs)
            {
                NHibernateUnitOfWorkFactory nestedUnitOfWorkFactory = new NHibernateUnitOfWorkFactory(config.NHibernateConfigurationFile);
                nestedUnitOfWorkFactory.RegisterSessionFactory(CreateSessionFactory(config));
                unitOfWorkFactory.Add(nestedUnitOfWorkFactory);
            }
            Kernel.AddComponentInstance <IUnitOfWorkFactory>(unitOfWorkFactory);
        }
        /// <summary>
        /// Adds the specified service to the service container, and optionally
        /// promotes the service to any parent service containers.
        /// </summary>
        /// <param name="serviceType">The type of service to add.</param>
        /// <param name="serviceInstance">The instance of the service to add.</param>
        /// <param name="promote">true to promote this request to any parent service containers.</param>
        public virtual void AddService(Type serviceType, object serviceInstance, bool promote)
        {
            if (serviceInstance is ServiceCreatorCallback)
            {
                AddService(serviceType, (ServiceCreatorCallback)serviceInstance, promote);
                return;
            }

            if (promote)
            {
                IServiceContainer parentServices = ParentServices;

                if (parentServices != null)
                {
                    parentServices.AddService(serviceType, serviceInstance, promote);
                    return;
                }
            }

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

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

            if (!(serviceInstance.GetType().IsCOMObject ||
                  serviceType.IsAssignableFrom(serviceInstance.GetType())))
            {
                throw new ArgumentException(String.Format(
                                                "Invalid service '{0}' for type '{1}'",
                                                serviceInstance.GetType().FullName, serviceType.FullName));
            }

            if (HasService(serviceType))
            {
                throw new ArgumentException(String.Format(
                                                "A service for type '{0}' already exists", serviceType.FullName));
            }

            String serviceName = GetServiceName(serviceType);

            Kernel.AddComponentInstance(serviceName, serviceType, serviceInstance);
        }
예제 #10
0
        private void ConfigureFactories(IConfiguration config,
                                        ISessionManager sessionManager, bool firstFactory)
        {
            String id = config.Attributes["id"];

            if (id == null || String.Empty.Equals(id))
            {
                throw new ConfigurationException("You must provide a " +
                                                 "valid 'id' attribute for the 'factory' node. This id is used as key for " +
                                                 "the ISessionFactory component registered on the container");
            }

            String alias = config.Attributes["alias"];

            if (!firstFactory && (alias == null || alias.Length == 0))
            {
                throw new ConfigurationException("You must provide a " +
                                                 "valid 'alias' attribute for the 'factory' node. This id is used to obtain " +
                                                 "the ISession implementation from the SessionManager");
            }
            else if (alias == null || alias.Length == 0)
            {
                alias = Constants.DefaultAlias;
            }

            Configuration cfg = new Configuration();

            ApplyConfigurationSettings(cfg, config.Children["settings"]);
            RegisterAssemblies(cfg, config.Children["assemblies"]);
            RegisterResources(cfg, config.Children["resources"]);

            // Registers the Configuration object

            Kernel.AddComponentInstance(String.Format("{0}.cfg", id), cfg);

            // Registers the ISessionFactory as a component

            ISessionFactory sessionFactory = cfg.BuildSessionFactory();

            Kernel.AddComponentInstance(id, typeof(ISessionFactory), sessionFactory);

            // Registers the ISessionFactory within the ISessionManager

            sessionManager.RegisterSessionFactory(alias, sessionFactory);
        }
예제 #11
0
        private void ConfigureSnapshot(IConfiguration engineConfig, IDictionary properties)
        {
            float period = GetSnapshotInterval(engineConfig);

            if (RequiresSnapshots(period))
            {
                if (engineConfig.Attributes["cleanupPolicyComponent"] == null)
                {
                    Kernel.AddComponentInstance(CleanupPolicyComponentPropertyKey, CleanUpAllFilesPolicy.Default);
                }

                properties.Add(SnapshotPeriodPropertyKey, period);
            }
            else
            {
                properties.Add(SnapshotPeriodPropertyKey, 0f);
            }
        }
예제 #12
0
        private void OnRootTypeRegistered(object sender, Type rootType)
        {
            if (!Kernel.HasComponent("activerecord.sessionfactory"))
            {
                Kernel.AddComponentInstance(
                    "activerecord.sessionfactory",
                    typeof(NHibernate.ISessionFactory),
                    new SessionFactoryDelegate((ISessionFactoryHolder)sender, rootType));
            }
            else
            {
                sessionFactoryCount++;

                Kernel.AddComponentInstance(
                    "activerecord.sessionfactory." + sessionFactoryCount.ToString(),
                    typeof(NHibernate.ISessionFactory),
                    new SessionFactoryDelegate((ISessionFactoryHolder)sender, rootType));
            }
        }
예제 #13
0
        private void OnSessionFactoryHolderCreated(Castle.ActiveRecord.Framework.ISessionFactoryHolder holder)
        {
            holder.OnRootTypeRegistered += new RootTypeHandler(OnRootTypeRegistered);

            if (!Kernel.HasComponent("activerecord.sessionfactoryholder"))
            {
                Kernel.AddComponentInstance(
                    "activerecord.sessionfactoryholder",
                    typeof(ISessionFactoryHolder), holder);
            }
            else
            {
                sessionFactoryHolderCount++;

                Kernel.AddComponentInstance(
                    "activerecord.sessionfactoryholder." + sessionFactoryCount.ToString(),
                    typeof(ISessionFactoryHolder), holder);
            }
        }
예제 #14
0
        /// <summary>
        /// Initializes the MethodValidatorFacility
        /// </summary>
        protected override void Init()
        {
            IValidatorRegistry registry;

            if (Kernel.HasComponent(typeof(IValidatorRegistry)))
            {
                registry = Kernel.Resolve <IValidatorRegistry>();
            }
            else
            {
                registry = new CachedValidationRegistry();
            }

            IValidatorRegistry adapter = new ParameterValidatorRegistryAdapter(registry);

            Kernel.AddComponentInstance("methodValidator.metaStore", new MethodValidatorMetaStore(adapter));

            Kernel.AddComponent("methodValidator.interceptor", typeof(MethodValidatorInterceptor));
            Kernel.AddComponent("methodValidator.contributor", typeof(MethodValidationContributor));
            Kernel.ComponentModelBuilder.AddContributor(new MethodValidatorComponentInspector());
        }
        /// <summary>
        /// Adds the specified <see cref="IComponent"/> to the <see cref="IContainer"/> at the end of the list,
        /// and assigns a name to the component.
        /// </summary>
        /// <param name="component">The <see cref="IComponent"/> to add.</param>
        /// <param name="name">The unique, case-insensitive name to assign to the component, or null.</param>
        public virtual void Add(IComponent component, String name)
        {
            if (component != null)
            {
                rwlock.AcquireWriterLock(Timeout.Infinite);

                try
                {
                    ISite site = component.Site;

                    if ((site == null) || (site.Container != this))
                    {
                        IContainerAdapterSite newSite = CreateSite(component, name);

                        try
                        {
                            Kernel.AddComponentInstance(newSite.EffectiveName, typeof(IComponent), component);
                        }
                        catch (ComponentRegistrationException ex)
                        {
                            throw new ArgumentException(ex.Message);
                        }

                        if (site != null)
                        {
                            site.Container.Remove(component);
                        }

                        component.Site = newSite;
                        sites.Add(newSite);
                    }
                }
                finally
                {
                    rwlock.ReleaseWriterLock();
                }
            }
        }
예제 #16
0
 private void DiscoverServices()
 {
     GraphNode[] nodes = this.Kernel.GraphNodes;
     foreach (ComponentModel model in nodes)
     {
         bool markedWithServiceContract = typeof(IServiceInterface).IsAssignableFrom(model.Service);
         if (!markedWithServiceContract)
         {
             foreach (object attr in model.Service.GetCustomAttributes(true))
             {
                 if (attr.ToString().EndsWith("ServiceContractAttribute"))
                 {
                     markedWithServiceContract = true;
                     break;
                 }
             }
         }
         if (markedWithServiceContract)
         {
             DynamicService service = new DynamicService(this, model.Service);
             Kernel.AddComponentInstance(Guid.NewGuid().ToString(), service);
         }
     }
 }
 private void RegisterLoggerFactory()
 {
     Kernel.AddComponentInstance("iloggerfactory", typeof(ILoggerFactory), factory);
 }
 private void RegisterDefaultILogger()
 {
     Kernel.AddComponentInstance("ilogger.default", typeof(ILogger), factory.Create("Default"));
 }
예제 #19
0
        protected override void Init()
        {
            var mapper = Mapper ?? new MemoizingMappingManager(new AttributesMappingManager());

            Kernel.AddComponentInstance <IReadOnlyMappingManager>(mapper);
            //Kernel.Register(Component.For<ISolrCache>().ImplementedBy<HttpRuntimeCache>());
            Kernel.Register(Component.For <ISolrConnection>().ImplementedBy <SolrConnection>()
                            .Parameters(Parameter.ForKey("serverURL").Eq(GetSolrUrl())));

            Kernel.Register(Component.For(typeof(ISolrDocumentActivator <>)).ImplementedBy(typeof(SolrDocumentActivator <>)));

            Kernel.Register(Component.For(typeof(ISolrDocumentResponseParser <>))
                            .ImplementedBy(typeof(SolrDocumentResponseParser <>)));
            Kernel.Register(Component.For <ISolrDocumentResponseParser <Dictionary <string, object> > >()
                            .ImplementedBy <SolrDictionaryDocumentResponseParser>());

            foreach (var parserType in new[] {
                typeof(ResultsResponseParser <>),
                typeof(HeaderResponseParser <>),
                typeof(FacetsResponseParser <>),
                typeof(HighlightingResponseParser <>),
                typeof(MoreLikeThisResponseParser <>),
                typeof(SpellCheckResponseParser <>),
                typeof(StatsResponseParser <>),
                typeof(CollapseResponseParser <>),
            })
            {
                Kernel.Register(Component.For(typeof(ISolrResponseParser <>)).ImplementedBy(parserType));
            }
            Kernel.Register(Component.For <ISolrHeaderResponseParser>().ImplementedBy <HeaderResponseParser <string> >());
            Kernel.Register(Component.For <ISolrExtractResponseParser>().ImplementedBy <ExtractResponseParser>());
            foreach (var validationRule in new[] {
                typeof(MappedPropertiesIsInSolrSchemaRule),
                typeof(RequiredFieldsAreMappedRule),
                typeof(UniqueKeyMatchesMappingRule),
            })
            {
                Kernel.Register(Component.For <IValidationRule>().ImplementedBy(validationRule));
            }
            Kernel.Resolver.AddSubResolver(new StrictArrayResolver(Kernel));
            Kernel.Register(Component.For(typeof(ISolrQueryResultParser <>))
                            .ImplementedBy(typeof(SolrQueryResultParser <>)));
            Kernel.Register(Component.For(typeof(ISolrQueryExecuter <>)).ImplementedBy(typeof(SolrQueryExecuter <>)));

            Kernel.Register(Component.For(typeof(ISolrDocumentSerializer <>))
                            .ImplementedBy(typeof(SolrDocumentSerializer <>)));
            Kernel.Register(Component.For <ISolrDocumentSerializer <Dictionary <string, object> > >()
                            .ImplementedBy <SolrDictionarySerializer>());

            Kernel.Register(Component.For(typeof(ISolrBasicOperations <>), typeof(ISolrBasicReadOnlyOperations <>))
                            .ImplementedBy(typeof(SolrBasicServer <>)));
            Kernel.Register(Component.For(typeof(ISolrOperations <>), typeof(ISolrReadOnlyOperations <>))
                            .ImplementedBy(typeof(SolrServer <>)));

            Kernel.Register(Component.For <ISolrFieldParser>()
                            .ImplementedBy <DefaultFieldParser>());

            Kernel.Register(Component.For <ISolrFieldSerializer>().ImplementedBy <DefaultFieldSerializer>());

            Kernel.Register(Component.For <ISolrQuerySerializer>().ImplementedBy <DefaultQuerySerializer>());
            Kernel.Register(Component.For <ISolrFacetQuerySerializer>().ImplementedBy <DefaultFacetQuerySerializer>());

            Kernel.Register(Component.For <ISolrDocumentPropertyVisitor>().ImplementedBy <DefaultDocumentVisitor>());

            Kernel.Register(Component.For <ISolrSchemaParser>().ImplementedBy <SolrSchemaParser>());
            Kernel.Register(Component.For <ISolrDIHStatusParser>().ImplementedBy <SolrDIHStatusParser>());
            Kernel.Register(Component.For <IMappingValidator>().ImplementedBy <MappingValidator>());

            AddCoresFromConfig();
            foreach (var core in cores)
            {
                RegisterCore(core);
            }
        }
예제 #20
0
 protected override void Init()
 {
     Kernel.AddComponentInstance <IMenuRegistry>(_topMenuRegistry);
     Kernel.AddComponentInstance <IMenuController>(_menuController);
     Kernel.ComponentCreated += Kernel_ComponentCreated;
 }
예제 #21
0
        private void ConfigureFactories(IConfiguration config,
                                        ISessionFactoryResolver sessionFactoryResolver, bool firstFactory)
        {
            String id = config.Attributes["id"];

            if (id == null || String.Empty.Equals(id))
            {
                throw new ConfigurationErrorsException("You must provide a " +
                                                       "valid 'id' attribute for the 'factory' node. This id is used as key for " +
                                                       "the ISessionFactory component registered on the container");
            }

            String alias = config.Attributes["alias"];

            if (!firstFactory && (alias == null || alias.Length == 0))
            {
                throw new ConfigurationErrorsException("You must provide a " +
                                                       "valid 'alias' attribute for the 'factory' node. This id is used to obtain " +
                                                       "the ISession implementation from the SessionManager");
            }
            else if (alias == null || alias.Length == 0)
            {
                alias = Constants.DefaultAlias;
            }

            if (config.Attributes["isWeb"] == "true")
            {
                appRootPath = HttpContext.Current.Server.MapPath("~/");
            }
            else
            {
                appRootPath = Application.StartupPath;
            }

            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();

            ApplyConfigurationSettings(cfg, config.Children["settings"]);
            RegisterAssemblies(cfg, config.Children["assemblies"]);
            RegisterResources(cfg, config.Children["resources"]);

            // Registers the Configuration object

            Kernel.AddComponentInstance(String.Format("{0}.cfg", id), cfg);

            // If a Session Factory level interceptor was provided, we use it

            if (Kernel.HasComponent("nhibernate.sessionfactory.interceptor"))
            {
                cfg.Interceptor = (IInterceptor)Kernel["nhibernate.sessionfactory.interceptor"];
            }

            // Registers the ISessionFactory as a component

            ISessionFactory sessionFactory = cfg.BuildSessionFactory();

            Kernel.AddComponentInstance(id, typeof(ISessionFactory), sessionFactory);

            // Registers the ISessionFactory within the ISessionFactoryResolver

            sessionFactoryResolver.RegisterAliasComponentIdMapping(alias, id);
        }
예제 #22
0
 public void Connect(string id, object instance, Type serviceType)
 {
     Kernel.AddComponentInstance(id, serviceType, instance);
 }
 protected override void Init()
 {
     Kernel.AddComponentInstance("eventPublisher.default", typeof(IEventPublisher), _eventPublisher);
     Kernel.ComponentCreated   += Kernel_ComponentCreated;
     Kernel.ComponentDestroyed += Kernel_ComponentDestroyed;
 }