Example #1
0
 public bool IsRegistered(Type t)
 {
     lock (_syncLock)
     {
         return(_kernel.CanResolve(t) != null);
     }
 }
Example #2
0
        public void MultipleConditionalBindingTest()
        {
            container.AutoBinding(Profiles.PROFILE_D);

            Assert.IsTrue(container.CanResolve <Master>());
            Assert.IsTrue(container.CanResolve <IMaster2>());
            Assert.IsFalse(container.CanResolve <IMaster>());
        }
Example #3
0
 public T GetService <T>()
 {
     if (sourceKernel.CanResolve <T>())
     {
         return(sourceKernel.Get <T>());
     }
     return(default(T));
 }
Example #4
0
        public TService GetInstance <TService>() where TService : class
        {
            if (!_kernel.CanResolve <TService>())
            {
                _kernel.Bind <TService>().ToSelf();
            }

            return(_kernel.Get <TService>());
        }
Example #5
0
        public IServiceRegister Register <TService>(Func <IServiceProvider, TService> serviceCreator) where TService : class
        {
            // EasyNetQ first adds the overrides, then the defaults, which would then set the default again.
            if (!_ninjectContainer.CanResolve <TService>())
            {
                _ninjectContainer.Bind <TService>().ToMethod(ctx => serviceCreator(this)).InSingletonScope();
            }

            return(this);
        }
Example #6
0
        private static void BindClass(Type targetType, IKernel kernel)
        {
            var binding = targetType.GetCustomAttribute <BindToAttribute>();

            foreach (var interfaceType in binding.InterfaceTypes)
            {
                if (kernel.CanResolve(interfaceType))
                {
                    continue;
                }

                switch (binding.Scope)
                {
                case Scope.Transient:
                    kernel.Bind(interfaceType).To(targetType).InTransientScope();
                    break;

                case Scope.Thread:
                    kernel.Bind(interfaceType).To(targetType).InThreadScope();
                    break;

                case Scope.Singleton:
                    kernel.Bind(interfaceType).To(targetType).InSingletonScope();
                    break;

                case Scope.Undefined:
                default:
                    throw new NotSupportedException("Defined Scope is not supported");
                }
            }
        }
Example #7
0
        internal static bool IsHttpEndpoint(Type controllerType)
        {
            if (controllerType == null)
            {
                throw new ArgumentNullException("controllerType");
            }

            var isController = controllerType != null &&
                               controllerType.IsClass &&
                               controllerType.IsVisible &&
                               controllerType.IsAbstract == false &&
                               typeof(IHttpController).IsAssignableFrom(controllerType);

            if (!isController)
            {
                return(false);
            }

            var dependancies = controllerType
                               .GetCustomAttributes(typeof(ControllerDependsOnAttribute), true)
                               .Cast <ControllerDependsOnAttribute>()
                               .SelectMany(a => a.Types);

            var isEnabled = !dependancies.Any() || dependancies.All(t => _kernel.CanResolve(t));

            return(isEnabled);
        }
Example #8
0
        /// <summary>
        /// Returns a value indicating whether the specified member should be injected.
        /// </summary>
        /// <param name="member">The member in question.</param>
        /// <returns>
        ///     <see langword="true"/> if the member should be injected; otherwise <see langword="false"/>.
        /// </returns>
        public bool ShouldInject(MemberInfo member)
        {
            if (member.MemberType != MemberTypes.Property)
            {
                return(false);
            }

            var propertyInfo = member as PropertyInfo;

            if (propertyInfo == null)
            {
                return(false);
            }

            if (propertyInfo.GetSetMethod() == null)
            {
                return(false);
            }

            // If the types are the same, or if the property is an interface or abstract class
            // that the declaring type implements (which would cause a cyclic resolution)
            if ((propertyInfo.PropertyType == propertyInfo.DeclaringType) ||
                ((propertyInfo.DeclaringType.IsAssignableFrom(propertyInfo.PropertyType))))
            {
                return(false);
            }

            var request = _kernel.CreateRequest(propertyInfo.PropertyType, null, EmptyParameters, true, false);

            return(_kernel.CanResolve(request));
        }
        public bool can_resolve_type(Type type)
        {
            ConfigureKernel();
            var  request           = kernel.CreateRequest(type, x => true, new IParameter[] { }, false, false);
            bool canResolveRequest = kernel.CanResolve(request);

            return(canResolveRequest);
        }
Example #10
0
        public void Warmup()
        {
            // We cannot use Orleans to obtain grains (to warm them up); Orleans only provides lazy grain references, and we'd
            // have to call a method on the grain to activate it, but there's no generic method we could call. So we instantiate
            // grains through Ninject instead of Orleans to register their dependencies in Ninject. When Orleans will instantiate
            // these grains, their non-transient dependencies will already be registered in Ninject, saving startup time.
            try
            {
                List <string> failedWarmupWarn = new List <string>();
                foreach (Type serviceClass in _orleansMapper.ServiceClassesTypes)
                {
                    try
                    {
                        foreach (Type parameterType in serviceClass.GetConstructors()
                                 .SelectMany(ctor => ctor.GetParameters().Select(p => p.ParameterType)).Distinct())
                        {
                            try
                            {
                                if (!_kernel.CanResolve(parameterType))
                                {
                                    if (_orleansInternalTypes.Contains(parameterType) || _orleansInternalTypesString.Any(x => parameterType.FullName.Contains(x)))
                                    {
                                        //No  waring on Orleans type
                                        continue;
                                    }

                                    failedWarmupWarn.Add($"Type {parameterType} of grain {serviceClass}");

                                    continue;
                                }

                                // Try to warm up dependency
                                _kernel.Get(parameterType);
                            }
                            catch//No exception handling needed. We try to warmup all constructor types. In case of failure, write the warning for non orleans types and go to the next type
                            {
                                failedWarmupWarn.Add($"Type {parameterType} of grain {serviceClass}");
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        _log.Warn($"Failed to warmup grain {serviceClass}", e);
                    }
                }

                if (failedWarmupWarn.Count > 0)
                {
                    _log.Warn($"Fail to warmup the following types:\n{string.Join("\n", failedWarmupWarn)}");
                }
            }

            catch (Exception ex)
            {
                _log.Warn("Failed to warmup grains", ex);
            }
        }
Example #11
0
        protected override JsonObjectContract CreateObjectContract(Type objectType)

        {
            var contract = base.CreateObjectContract(objectType);

            if ((bool)_kernel.CanResolve(objectType))
            {
                contract.DefaultCreator = () => _kernel.Get(objectType);
            }
            return(contract);
        }
        public static IKernel RegisterPopupNavigationService <TService>(this IKernel kernel)
            where TService : PopupPageNavigationService
        {
            if (!kernel.CanResolve <IPopupNavigation>())
            {
                kernel.Bind <IPopupNavigation>().ToConstant(PopupNavigation.Instance).InSingletonScope();
            }

            kernel.Bind <INavigationService>().To <TService>().Named(_navigationServiceName);
            return(kernel);
        }
Example #13
0
        /// <summary>
        /// Determines whether the specified request can be resolved.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>
        ///     <c>True</c> if the request can be resolved; otherwise, <c>false</c>.
        /// </returns>
        public override bool CanResolve(IRequest request)
        {
            var canResolve = base.CanResolve(request);

            if (!canResolve && _parent != null)
            {
                return(_parent.CanResolve(request));
            }

            return(canResolve);
        }
Example #14
0
        public void Warmup()
        {
            // We cannot use Orleans to obtain grains (to warm them up); Orleans only provides lazy grain references, and we'd
            // have to call a method on the grain to activate it, but there's no generic method we could call. So we instantiate
            // grains through Ninject instead of Orleans to register their dependencies in Ninject. When Orleans will instantiate
            // these grains, their non-transient dependencies will already be registered in Ninject, saving startup time.
            try
            {
                List <string> failedWarmupWarn = new List <string>();
                List <string> failedWarmupInfo = new List <string>();
                foreach (Type serviceClass in _orleansMapper.ServiceClassesTypes)
                {
                    try
                    {
                        foreach (Type parameterType in serviceClass.GetConstructors().SelectMany(ctor => ctor.GetParameters().Select(p => p.ParameterType)).Distinct())
                        {
                            if (_kernel.CanResolve(parameterType))
                            {
                                _kernel.Get(parameterType);
                                continue;
                            }

                            if (_orleansInternalTypes.Contains(parameterType))
                            {
                                failedWarmupInfo.Add($"Type {parameterType} of grain {serviceClass}");
                            }
                            else
                            {
                                failedWarmupWarn.Add($"Type {parameterType} of grain {serviceClass}");
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        _log.Warn($"Failed to warmup grain {serviceClass}", e);
                    }
                }

                if (failedWarmupInfo.Count > 0)
                {
                    _log.Info(l => l($"Can't warmup the following types:\n{string.Join("\n", failedWarmupInfo)}"));
                }

                if (failedWarmupWarn.Count > 0)
                {
                    _log.Warn($"Fail to warmup the following types:\n{string.Join("\n", failedWarmupWarn)}");
                }
            }
            catch (Exception ex)
            {
                _log.Warn("Failed to warmup grains", ex);
            }
        }
Example #15
0
        /// <inheritdoc />
        public bool Remove(ServiceDescriptor item)
        {
            if (item is null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            if (_kernel.CanResolve(item.ServiceType))
            {
                _kernel.Unbind(item.ServiceType);
            }

            return(_bindingByModuleName[DirectRegister].Remove(item));
        }
Example #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="kernel"></param>
        /// <param name="binding"></param>
        /// <returns></returns>
        private ConstructorMetadata FindBestConstructor(IKernel kernel, IBinding binding)
        {
            if (metadata.TargetConstructors.Length == 0)
            {
                throw new InvalidOperationException(
                          String.Format(CultureInfo.InvariantCulture, "No constructor avaiable. type = {0}", TargetType.Name));
            }

            for (var i = 0; i < metadata.TargetConstructors.Length; i++)
            {
                var match = true;
                var cm    = metadata.TargetConstructors[i];

                var parameters = cm.Parameters;
                for (var j = 0; j < parameters.Length; j++)
                {
                    var parameter = parameters[j];
                    var pi        = parameter.Parameter;

                    // Constructor argument
                    if (binding.ConstructorArguments.GetParameter(pi.Name) != null)
                    {
                        continue;
                    }

                    // Multiple
                    if (parameter.ElementType != null)
                    {
                        continue;
                    }

                    // Resolve
                    if (kernel.CanResolve(pi.ParameterType, cm.Constraints[j]))
                    {
                        continue;
                    }

                    match = false;
                    break;
                }

                if (match)
                {
                    return(cm);
                }
            }

            throw new InvalidOperationException(
                      String.Format(CultureInfo.InvariantCulture, "Constructor parameter unresolved. type = {0}", TargetType.Name));
        }
        /// <summary>
        ///     Determines whether the specified request can be resolved.
        /// </summary>
        /// <param name="service">The specified service type.</param>
        /// <param name="name">The specified binding name.</param>
        /// <returns>
        ///     <c>True</c> if the specified service has been resolved; otherwise, <c>false</c>.
        /// </returns>
        public bool CanResolve(Type service, string name = null)
        {
            Should.NotBeNull(service, "service");
            if (IsDisposed)
            {
                return(false);
            }
            Func <IBindingMetadata, bool> canResolve = null;

            if (name != null)
            {
                canResolve = metadata => metadata.Name == name;
            }
            IRequest req = _kernel.CreateRequest(service, canResolve, Empty.Array <IParameter>(), false, true);

            return(_kernel.CanResolve(req, true));
        }
        /// <summary>
        /// Stores the bus instance
        /// </summary>
        public void SetBus(IBus bus)
        {
            if (_kernel.CanResolve(typeof(IBus)))
            {
                throw new InvalidOperationException("Cannot register IBus because it has already been registered. If you want to host multiple Rebus instances in a single process, please use separate container instances for them.");
            }

            _kernel.Bind <IBus>().ToConstant(bus);

            _kernel.Bind <ISyncBus>().ToMethod(c => bus.Advanced.SyncBus);

            _kernel.Bind <IMessageContext>().ToMethod(c =>
            {
                var currentMessageContext = MessageContext.Current;
                if (currentMessageContext == null)
                {
                    throw new InvalidOperationException(
                        "Attempted to inject the current message context from MessageContext.Current, but it was null! Did you attempt to resolve IMessageContext from outside of a Rebus message handler?");
                }
                return(currentMessageContext);
            });

            ResolutionExtensions.Get <IBus>(_kernel);
        }
        /// <summary>
        /// Determines whether the specified component type has a component.
        /// </summary>
        /// <param name="componentType">
        /// Type of the component.
        /// </param>
        /// <returns>
        /// <c>true</c> if the specified component type has a component; otherwise, <c>false</c>.
        /// </returns>
        public bool HasComponent(Type componentType)
        {
            var request = kernel.CreateRequest(componentType, null, new IParameter[0], false, true);

            return(kernel.CanResolve(request));
        }
Example #20
0
 public static T TryResolve <T>()
 {
     return(kernel.CanResolve <T>() ? kernel.Get <T>() : default(T));
 }
Example #21
0
 /// <summary>
 /// Basic method to find out if the service, <paramref name="serviceType"/>, has been registered with the <param name="kernel"/>
 /// </summary>
 /// <param name="kernel"></param>
 /// <param name="serviceType"></param>
 /// <returns></returns>
 public static bool IsRegistered(this IKernel kernel, Type serviceType)
 {
     return(kernel.CanResolve(kernel.CreateRequest(serviceType, meta => true, new List <IParameter>(), false, false)));
 }
 /// <inheritdoc />
 public bool HasRegistration(Type serviceType)
 {
     return(_kernel.CanResolve(serviceType));
 }
 /// <summary>
 /// Return true if the given type is registered with the container.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public override bool IsRegistered(Type type)
 {
     return(container.CanResolve(container.CreateRequest(type, null, new List <IParameter>(), false, false)));
 }
Example #24
0
 public bool CanResolve(Type type)
 {
     return((bool)_kernel.CanResolve(type));
 }
Example #25
0
 public bool IsRegistered <TService>() => _kernel.CanResolve <TService>();
Example #26
0
 public static bool IsRegistered(this IKernel kernel, Type type)
 {
     return(kernel.CanResolve(kernel.CreateRequest(type, _ => true, new IParameter[] { }, false, false)));
 }
 /// <inheritdoc />
 public bool HasRegistration(Type serviceType, string contract = null)
 {
     return(_kernel.CanResolve(serviceType));
 }
Example #28
0
 /// <summary>
 /// Checking if TService can be resolved is a workaround to the issue that Ninject
 /// does not allow TService to be registered multiple times such that the behavior
 /// of DefaultServiceProvider can be emulated using Ninject.
 /// </summary>
 /// <typeparam name="TService"></typeparam>
 /// <returns></returns>
 private bool IsAlreadyRegistered <TService>() where TService : class
 {
     return(_ninjectContainer.CanResolve <TService>());
 }
Example #29
0
 /// <inheritdoc />
 public bool IsRegistered(Type type) => _kernel.CanResolve(type);
Example #30
0
 /// <summary>
 /// Determines whether the specified service type is bindable.
 /// </summary>
 /// <param name="serviceType">The type of the service.</param>
 /// <param name="kernel">The kernel.</param>
 /// <returns>
 /// 	<see langword="true"/> if the specified service type is bindable; otherwise, <see langword="false"/>.
 /// </returns>
 public static bool IsBindable(this Type serviceType, IKernel kernel)
 {
     var request = kernel.CreateRequest(serviceType, null, new IParameter[] { }, false);
     return kernel.CanResolve(request);
 }
Example #31
0
 public bool IsRegistered <T>()
 {
     return(_kernel.CanResolve <T>());
 }