Example #1
0
        public void StartAllIStartable()
        {
            HealthChecks.RegisterHealthCheck("Startable", (Func <HealthCheckResult>)StartableHealtCheck);
            IHandler[] handlers = Kernel.GetAssignableHandlers(typeof(object));
            IEnumerable <HandlerInfo> startableHandlers = GetStartableHandlers(handlers);

            foreach (var handlerInfo in startableHandlers.OrderBy(h => h.Priority))
            {
                try
                {
                    handlerInfo.Handler.Resolve(CreationContext.CreateEmpty());
                    _logger.InfoFormat("Component {0} started correctly.", handlerInfo.Description);
                }
                catch (Exception ex)
                {
                    _logger.ErrorFormat(ex, "Cannot start component {0} because it raised exception. Retry in {1} seconds.", handlerInfo.Description, _timeoutInSecondsBeforeRetryRestartFailedServices);
                    handlerInfo.StartException = ex;
                    _handlersWithStartError.Add(handlerInfo);
                }
            }
            if (_handlersWithStartError.Count > 0)
            {
                _retryStartTimer = new System.Threading.Timer(
                    RetryStartTimerCallback,
                    null,
                    1000 * _timeoutInSecondsBeforeRetryRestartFailedServices, //Due time
                    1000 * _timeoutInSecondsBeforeRetryRestartFailedServices  //Period
                    );
            }
        }
Example #2
0
 private void RetryStartTimerCallback(object state)
 {
     _retryCount++;
     if (!_executing)
     {
         try
         {
             _executing = true;
             foreach (var handlerInfo in _handlersWithStartError.ToList())
             {
                 try
                 {
                     handlerInfo.Handler.Resolve(CreationContext.CreateEmpty());
                     _handlersWithStartError.Remove(handlerInfo);
                     _logger.InfoFormat("Component {0} started correctly after {1} retries.", handlerInfo.Description, _retryCount);
                 }
                 catch (Exception ex)
                 {
                     //Handler still failed start, leave it into collection and will be restarted.
                     _logger.ErrorFormat(ex, "Cannot start component {0} because it raised exception. Retry in {1} seconds.", handlerInfo.Description, _timeoutInSecondsBeforeRetryRestartFailedServices);
                 }
             }
         }
         finally
         {
             _executing = false;
             if (_handlersWithStartError.Count == 0)
             {
                 _retryStartTimer.Dispose();
             }
         }
     }
 }
Example #3
0
        private void onComponentRegistered(string key, IHandler handler)
        {
            if ((bool)(handler.ComponentModel.ExtendedProperties["IsSerializerFactory"] ?? false))
            {
                if (handler.CurrentState == HandlerState.WaitingDependency)
                {
                    m_SerializerFactoryWaitList.Add(handler);
                }
                else
                {
                    registerSerializerFactory(handler);
                }
            }

            var messageHandlerFor = handler.ComponentModel.ExtendedProperties["MessageHandlerFor"] as string[];

            if (messageHandlerFor != null && messageHandlerFor.Length > 0)
            {
                if (handler.CurrentState == HandlerState.WaitingDependency)
                {
                    m_MessageHandlerWaitList.Add(handler);
                }
                else
                {
                    handler.Resolve(CreationContext.CreateEmpty());
                }
            }

            processWaitList();
        }
Example #4
0
        public override bool ReleaseCore(Burden burden)
        {
            var genericType = ProxyUtil.GetUnproxiedType(burden.Instance);

            var handler = GetSubHandler(CreationContext.CreateEmpty(), genericType);

            return(handler.Release(burden));
        }
        public void TestCustom()
        {
            kernel.Register(Component.For(typeof(IComponent)).ImplementedBy(typeof(CustomComponent)).Named("a"));

            IHandler handler = kernel.GetHandler("a");

            IComponent instance1 = handler.Resolve(CreationContext.CreateEmpty()) as IComponent;

            Assert.IsNotNull(instance1);
        }
        private bool TryRegisterSerializerFactory(IHandler handler)
        {
            var factory = handler.TryResolve(CreationContext.CreateEmpty());

            if (factory == null)
            {
                return(false);
            }
            m_MessagingEngine.SerializationManager.RegisterSerializerFactory(factory as ISerializerFactory);
            return(true);
        }
Example #7
0
 /// <summary>
 ///   Request the component instance
 /// </summary>
 /// <param name = "handler"></param>
 private bool TryStart(IHandler handler)
 {
     try
     {
         inStart = true;
         return(handler.TryResolve(CreationContext.CreateEmpty()) != null);
     }
     finally
     {
         inStart = false;
     }
 }
Example #8
0
        private void processWaitList()
        {
            foreach (var handler in m_MessageHandlerWaitList.Where(handler => handler.CurrentState == HandlerState.Valid))
            {
                handler.Resolve(CreationContext.CreateEmpty());
            }

            foreach (var factoryHandler in m_SerializerFactoryWaitList.ToArray().Where(factoryHandler => factoryHandler.CurrentState == HandlerState.Valid))
            {
                registerSerializerFactory(factoryHandler);
                m_SerializerWaitList.Remove(factoryHandler);
            }
        }
        public void TryResolvingViaChildKernelShouldNotThrowException()
        {
            using (var childKernel = new DefaultKernel())
            {
                Kernel.Register(Component.For <BookStore>());
                Kernel.AddChildKernel(childKernel);
                var handler = childKernel.GetHandler(typeof(BookStore));

                // Assert setup invariant
                Assert.IsInstanceOf <ParentHandlerWrapper>(handler);

                Assert.DoesNotThrow(() => handler.TryResolve(CreationContext.CreateEmpty()));
            }
        }
        public void TestSingleton()
        {
            kernel.Register(Component.For(typeof(IComponent)).ImplementedBy(typeof(SingletonComponent)).Named("a"));

            IHandler handler = kernel.GetHandler("a");

            IComponent instance1 = handler.Resolve(CreationContext.CreateEmpty()) as IComponent;
            IComponent instance2 = handler.Resolve(CreationContext.CreateEmpty()) as IComponent;

            Assert.IsNotNull(instance1);
            Assert.IsNotNull(instance2);

            Assert.IsTrue(instance1.Equals(instance2));
            Assert.IsTrue(instance1.ID == instance2.ID);
        }
        public void TestTransient()
        {
            Kernel.Register(Component.For <IComponent>().ImplementedBy(typeof(TransientComponent)).Named("a"));

            var handler = Kernel.GetHandler("a");

            var instance1 = handler.Resolve(CreationContext.CreateEmpty()) as IComponent;
            var instance2 = handler.Resolve(CreationContext.CreateEmpty()) as IComponent;

            Assert.IsNotNull(instance1);
            Assert.IsNotNull(instance2);

            Assert.IsTrue(!instance1.Equals(instance2));
            Assert.IsTrue(instance1.ID != instance2.ID);
        }
Example #12
0
        public override object PerformConversion(String value, Type targetType)
        {
            if (ReferenceExpressionUtil.IsReference(value))
            {
                string newValue = ReferenceExpressionUtil.ExtractComponentName(value);
                var    handler  = Context.Kernel.LoadHandlerByName(newValue, targetType, null);
                if (handler == null)
                {
                    throw new ConverterException(string.Format("Component '{0}' was not found in the container.", newValue));
                }

                return(handler.Resolve(Context.CurrentCreationContext ?? CreationContext.CreateEmpty()));
            }
            throw new NotImplementedException();
        }
Example #13
0
        public override object PerformConversion(String value, Type targetType)
        {
            var componentName = ReferenceExpressionUtil.ExtractComponentKey(value);

            if (componentName == null)
            {
                throw new ConverterException(string.Format("Could not convert expression '{0}' to type '{1}'. Expecting a reference override like ${{some key}}", value,
                                                           targetType.FullName));
            }

            var handler = Context.Kernel.LoadHandlerByKey(componentName, targetType, null);

            if (handler == null)
            {
                throw new ConverterException(string.Format("Component '{0}' was not found in the container.", componentName));
            }

            return(handler.Resolve(Context.CurrentCreationContext ?? CreationContext.CreateEmpty()));
        }
        public void RegisterFacility_WithControlProxyHook_WorksFine()
        {
            var type       = typeof(SynchronizeFacility).FullName;
            var container2 = new WindsorContainer();
            var facNode    = new MutableConfiguration("facility");

            facNode.Attributes["type"] = type;
            facNode.Attributes[Constants.ControlProxyHookAttrib] = typeof(DummyProxyHook).AssemblyQualifiedName;
            container2.Kernel.ConfigurationStore.AddFacilityConfiguration(type, facNode);
            container2.AddFacility(new SynchronizeFacility());

            container2.Register(Component.For <DummyForm>().Named("dummy.form.class"));
            var model   = container2.Kernel.GetHandler("dummy.form.class").ComponentModel;
            var options = model.ObtainProxyOptions(false);

            Assert.IsNotNull(options, "Proxy options should not be null");
            Assert.IsTrue(options.Hook.Resolve(container2.Kernel, CreationContext.CreateEmpty()) is DummyProxyHook,
                          "Proxy hook should be a DummyProxyHook");
        }
Example #15
0
 internal static void AddBehaviors <T>(IKernel kernel, WcfExtensionScope scope,
                                       KeyedByTypeCollection <T> behaviors, IWcfBurden burden,
                                       Predicate <T> predicate)
 {
     foreach (var handler in FindExtensions <T>(kernel, scope))
     {
         T behavior = (T)handler.Resolve(CreationContext.CreateEmpty());
         if (predicate == null || predicate(behavior))
         {
             if (behaviors != null)
             {
                 behaviors.Add(behavior);
             }
             if (burden != null)
             {
                 burden.Add(behavior);
             }
         }
     }
 }
        /// <summary>
        ///   Applies the synchronization support to the model.
        /// </summary>
        /// <param name = "model">The model.</param>
        /// <param name = "kernel">The kernel.</param>
        private void ApplySynchronization(ComponentModel model, IKernel kernel)
        {
            var options = model.ObtainProxyOptions();

            model.Interceptors.Add(new InterceptorReference(typeof(SynchronizeInterceptor)));

            var metaInfo = metaStore.GetMetaFor(model.Implementation);

            if (metaInfo != null)
            {
                IInterceptorSelector userSelector = null;
                if (options.Selector != null)
                {
                    userSelector = options.Selector.Resolve(kernel, CreationContext.CreateEmpty());
                }

                options.Selector = new InstanceReference <IInterceptorSelector>(new SynchronizeInterceptorSelector(metaInfo, userSelector));
                foreach (var reference in metaInfo.GetUniqueSynchContextReferences())
                {
                    reference.Attach(model);
                }
            }
        }
        private void BindEnvironment(object instance, EnvironmentScope envScope)
        {
            var resolver = _kernel.Resolver;
            var context  = CreationContext.CreateEmpty();

            instance = ProxyUtil.GetUnproxiedInstance(instance);

            foreach (var property in _componentModel.Properties
                     .Where(property => envScope.Contains(property.Property.PropertyType)))
            {
                try
                {
                    var value = resolver.Resolve(context, context.Handler, _componentModel, property.Dependency);
                    if (value == null)
                    {
                        continue;
                    }
                    if (value == EnvironmentScope.Null)
                    {
                        value = null;
                    }
                    try
                    {
                        var setMethod = property.Property.GetSetMethod();
                        setMethod.Invoke(instance, new[] { value });
                    }
                    catch
                    {
                        // ignore
                    }
                }
                catch
                {
                    // ignore
                }
            }
        }
        public void TestPerThread()
        {
            Kernel.Register(Component.For <IComponent>().ImplementedBy(typeof(PerThreadComponent)).Named("a"));

            var handler = Kernel.GetHandler("a");

            var instance1 = handler.Resolve(CreationContext.CreateEmpty()) as IComponent;
            var instance2 = handler.Resolve(CreationContext.CreateEmpty()) as IComponent;

            Assert.IsNotNull(instance1);
            Assert.IsNotNull(instance2);

            Assert.IsTrue(instance1.Equals(instance2));
            Assert.IsTrue(instance1.ID == instance2.ID);

            var thread = new Thread(OtherThread);

            thread.Start();
            thread.Join();

            Assert.IsNotNull(instance3);
            Assert.IsTrue(!instance1.Equals(instance3));
            Assert.IsTrue(instance1.ID != instance3.ID);
        }
Example #19
0
 private void processWaitList()
 {
     foreach (var pair in m_WaitList.ToArray().Where(pair => pair.Key.CurrentState == HandlerState.Valid && pair.Key.TryResolve(CreationContext.CreateEmpty()) != null))
     {
         pair.Value(pair.Key);
         m_WaitList.Remove(pair.Key);
     }
 }
Example #20
0
 protected virtual void Start(IHandler handler)
 {
     handler.Resolve(CreationContext.CreateEmpty());
 }
Example #21
0
 public IEnumerable <IHandler> GetAllHandlersFor(Type type)
 {
     return(from h in container.Kernel.GetAssignableHandlers(type)
            select(IHandler) new DefaultHandler(null, h.ComponentModel.Implementation, () => h.Resolve(CreationContext.CreateEmpty())));
 }
        private void OtherThread()
        {
            var handler = Kernel.GetHandler("a");

            instance3 = handler.Resolve(CreationContext.CreateEmpty()) as IComponent;
        }
        private bool InvokeInSynchronizationContext(IInvocation invocation)
        {
            if (metaInfo != null)
            {
                IHandler handler = null;
                SynchronizationContext syncContext     = null;
                SynchronizationContext prevSyncContext = null;
                var methodInfo     = invocation.MethodInvocationTarget;
                var syncContextRef = metaInfo.GetSynchronizedContextFor(methodInfo);

                if (syncContextRef != null)
                {
                    switch (syncContextRef.ReferenceType)
                    {
                    case SynchronizeContextReferenceType.Key:
                        handler = kernel.GetHandler(syncContextRef.ComponentKey);
                        break;

                    case SynchronizeContextReferenceType.Interface:
                        handler = kernel.GetHandler(syncContextRef.ServiceType);
                        break;
                    }

                    if (handler == null)
                    {
                        throw new ApplicationException("The synchronization context could not be resolved.  Did you forget to register it in the container?");
                    }

                    syncContext = handler.Resolve(CreationContext.CreateEmpty()) as SynchronizationContext;

                    if (syncContext == null)
                    {
                        throw new ApplicationException(string.Format("{0} does not implement {1}",
                                                                     syncContextRef, typeof(SynchronizationContext).FullName));
                    }

                    prevSyncContext = SynchronizationContext.Current;
                }
                else
                {
                    syncContext = SynchronizationContext.Current;
                }

                if (syncContext != activeSyncContext)
                {
                    try
                    {
                        var result = CreateResult(invocation);

                        if (prevSyncContext != null)
                        {
                            SynchronizationContext.SetSynchronizationContext(syncContext);
                        }

                        if (syncContext.GetType() == typeof(SynchronizationContext))
                        {
                            InvokeSynchronously(invocation, result);
                        }
                        else
                        {
                            syncContext.Send(state =>
                            {
                                activeSyncContext = syncContext;
                                try
                                {
                                    InvokeSafely(invocation, result);
                                }
                                finally
                                {
                                    activeSyncContext = null;
                                }
                            }, null);
                        }
                    }
                    finally
                    {
                        if (prevSyncContext != null)
                        {
                            SynchronizationContext.SetSynchronizationContext(prevSyncContext);
                        }
                    }
                }
                else
                {
                    InvokeSynchronously(invocation, null);
                }

                return(true);
            }

            return(false);
        }
Example #24
0
        private bool InvokeInSynchronizationContext(IInvocation invocation)
        {
            if (metaInfo == null)
            {
                return(false);
            }

            SynchronizationContext syncContext     = null;
            SynchronizationContext prevSyncContext = null;
            var methodInfo     = invocation.MethodInvocationTarget;
            var syncContextRef = metaInfo.GetSynchronizedContextFor(methodInfo);

            if (syncContextRef != null)
            {
                syncContext     = syncContextRef.Resolve(kernel, CreationContext.CreateEmpty());
                prevSyncContext = SynchronizationContext.Current;
            }
            else
            {
                syncContext = SynchronizationContext.Current;
            }

            if (syncContext != activeSyncContext)
            {
                try
                {
                    var result = CreateResult(invocation);

                    if (prevSyncContext != null)
                    {
                        SynchronizationContext.SetSynchronizationContext(syncContext);
                    }

                    if (syncContext.GetType() == typeof(SynchronizationContext))
                    {
                        InvokeSynchronously(invocation, result);
                    }
                    else
                    {
                        syncContext.Send(state =>
                        {
                            activeSyncContext = syncContext;
                            try
                            {
                                InvokeSafely(invocation, result);
                            }
                            finally
                            {
                                activeSyncContext = null;
                            }
                        }, null);
                    }
                }
                finally
                {
                    if (prevSyncContext != null)
                    {
                        SynchronizationContext.SetSynchronizationContext(prevSyncContext);
                    }
                }
            }
            else
            {
                InvokeSynchronously(invocation, null);
            }

            return(true);
        }
 /// <summary>
 /// Request the component instance
 /// </summary>
 /// <param name="handler"/>
 private bool TryStart(IHandler handler)
 {
     return(handler.TryResolve(CreationContext.CreateEmpty()) != null);
 }
Example #26
0
 private void Start(IHandler handler)
 {
     handler.Resolve(CreationContext.CreateEmpty());
 }