public bool HasAnyProjectors(Type aggregateType) { var bindings = kernel.GetBindings( typeof(IEFCoreEntityEventProjector <>).MakeGenericType(aggregateType)); return(bindings.Any()); }
/// <inheritdoc /> public void RegisterDefault <TService, TImplementation>() where TService : class where TImplementation : class, TService { if (kernel.GetBindings(typeof(TService)).Any()) { return; } kernel.Bind <TService>().To <TImplementation>(); }
private static void RemoveBindings(Type TInterface) { var binds = kernel.GetBindings(TInterface); foreach (var bindRemove in binds) { kernel.RemoveBinding(bindRemove); } }
public static IRabbitMqReceiveEndpointConfigurator ConfigureConsumersForNinject( this IRabbitMqReceiveEndpointConfigurator ep, IEnumerable <Assembly> assembliesToScan, IKernel kernel) { //Scan all to get the consumers. var consumerInterface = typeof(IConsumer <>); foreach (var assembly in assembliesToScan) { var consumerTypes = assembly.GetModules() .SelectMany(m => m.GetTypes()) .Where( t => t.GetInterfaces() .Any(i => i.IsGenericType && !i.ContainsGenericParameters && i.GetGenericTypeDefinition() == consumerInterface)); foreach (var consumerType in consumerTypes) { var consumerTypeInterface = consumerType.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == consumerInterface); var messageType = (consumerTypeInterface?.GenericTypeArguments)?.SingleOrDefault(i => typeof(IMessage).IsAssignableFrom(i)); var genericFaultHandlerType = typeof(TestGenericFaultConsumer <>); if (!kernel.GetBindings(consumerType).Any()) { kernel.Bind(consumerType).ToSelf(); } ep.Consumer(consumerType, type => kernel.Get(type)); if (messageType != null) { var faultHandler = genericFaultHandlerType.MakeGenericType(messageType); if (!kernel.GetBindings(faultHandler).Any()) { kernel.Bind(faultHandler).ToSelf(); } ep.Consumer(faultHandler, type => kernel.Get(type)); } } } return(ep); }
public IDependencyResolver Register <T1, T2>(string name) where T2 : T1 { var bindings = _kernel.GetBindings(typeof(T1)); var binding = bindings.SingleOrDefault(x => x.Metadata.Name == name); if (binding != null) { _kernel.RemoveBinding(binding); } _kernel.Bind <T1>().To <T2>().Named(name); return(this); }
public IReferenceRatingProvider CreateReferenceRatingProvider() { string providerName = _ratingSettings.SelectedReferenceRatingProvider; IReferenceRatingProvider referenceRatingProvider = _resolutionRoot.TryGet <IReferenceRatingProvider>(providerName); if (referenceRatingProvider == null) { var binding = _kernel.GetBindings(typeof(IReferenceRatingProvider)).First(); providerName = binding.Metadata.Name; _ratingSettings.SelectedReferenceRatingProvider = providerName; return(_resolutionRoot.Get <IReferenceRatingProvider>(providerName)); } return(referenceRatingProvider); }
/// <summary> /// Returns the set of candidates that may satisfiy this navigation request. /// </summary> /// <param name="region">The region containing items that may satisfy the navigation request.</param> /// <param name="candidateNavigationContract">The candidate navigation target.</param> /// <returns>An enumerable of candidate objects from the <see cref="IRegion"/></returns> protected override IEnumerable <object> GetCandidatesFromRegion(IRegion region, string candidateNavigationContract) { if (candidateNavigationContract == null || candidateNavigationContract.Equals(string.Empty)) { throw new ArgumentNullException(nameof(candidateNavigationContract)); } var contractCandidates = base.GetCandidatesFromRegion(region, candidateNavigationContract); if (!contractCandidates.Any()) { // find by name var matchingRegistration = _kernel .GetBindings(typeof(object)) .FirstOrDefault(r => candidateNavigationContract.Equals( r.BindingConfiguration.Metadata.Name, StringComparison.Ordinal)); if (matchingRegistration == null) { return(contractCandidates); } var kernelTarget = matchingRegistration.ProviderCallback?.Target; var typeCandidateName = kernelTarget?.GetType().GetField("prototype").GetValue(kernelTarget).ToString(); contractCandidates = base.GetCandidatesFromRegion(region, typeCandidateName); } return(contractCandidates); }
/// <summary> /// Checkes whether a binding exists for a given target on the specified kernel. /// </summary> /// <param name="kernel">The kernel.</param> /// <param name="context">The context.</param> /// <param name="target">The target.</param> /// <returns>Whether a binding exists for the target in the given context.</returns> protected virtual bool BindingExists(IKernel kernel, IContext context, ITarget target) { var targetType = GetTargetType(target); return(kernel.GetBindings(targetType).Any(b => !b.IsImplicit) || target.HasDefaultValue); }
public ControllerMapper(ITypeFinder typeFinder, IContentTypeManager definitionManager, IKernel kernel) { IList<ControlsAttribute> controllerDefinitions = FindControllers(typeFinder); foreach (ContentType id in definitionManager.GetContentTypes()) { IAdapterDescriptor controllerDefinition = GetControllerFor(id.ItemType, controllerDefinitions); if (controllerDefinition != null) { string controllerName = GetControllerName(controllerDefinition.AdapterType, controllerDefinition.AreaName); ControllerMap[id.ItemType] = controllerDefinition.ControllerName; AreaMap[id.ItemType] = controllerDefinition.AreaName; if (!kernel.GetBindings(typeof(IController)).Any(b => b.Metadata.Name == controllerName)) kernel.Bind<IController>().To(controllerDefinition.AdapterType) .InTransientScope() .Named(controllerName); IList<IPathFinder> finders = PathDictionary.GetFinders(id.ItemType); if (0 == finders.Where(f => f is ActionResolver).Count()) { // TODO: Get the list of methods from a list of actions retrieved from somewhere within MVC var methods = controllerDefinition.AdapterType.GetMethods().Select(m => m.Name).ToArray(); var actionResolver = new ActionResolver(this, methods); PathDictionary.PrependFinder(id.ItemType, actionResolver); } } } }
private static object ResolveInterface([NotNull] IKernel kernel, [NotNull] Type interfaceType, [NotNull] Type interfaceArgument) { var isContravariantTemplate = IsContravariantTemplate(interfaceType); var activation = new Stack <Type>(); var templateArgument = interfaceArgument; while (templateArgument != null) { activation.Push(templateArgument); var closedTemplateType = interfaceType.CloseTemplate(new[] { templateArgument }); var bindings = kernel.GetBindings(closedTemplateType); // ReSharper disable PossibleMultipleEnumeration => bindings.Any should return if there is any element, so it will not enumerate the bindings, // and bindings.ToList() will enumerate only it, when registration of the newly found bindings should occurs. => no multiple enumeration of sequence. if (bindings.Any()) { CacheResolutionIfNewlyResolved(kernel, interfaceType, interfaceArgument, templateArgument, bindings); return(kernel.Get(closedTemplateType)); } // ReSharper restore PossibleMultipleEnumeration templateArgument = isContravariantTemplate ? templateArgument.IntrospectionBaseType() : null; } throw ActivationExceptionExtensions.Create(interfaceType, interfaceArgument, activation); }
protected virtual void RegisterCustomBehavior() { if (!kernel.GetBindings(typeof(ServiceHost)).Any()) { kernel.Bind <ServiceHost>().To <NinjectServiceHost>(); } }
private bool ShouldInject(PropertyInfo propertyInfo) { if (propertyInfo == null) { return(false); } if (!propertyInfo.CanWrite) { return(false); } Type propertyType = propertyInfo.PropertyType; string assemblyName = propertyType.Assembly.GetName().Name; if (KnownAssemblies != null) { if (!KnownAssemblies.Contains(propertyType.Assembly)) { return(false); } } var has = kernel.GetBindings(propertyType).FirstOrDefault() != null; return(has); }
public LotHostEntry TryHost(int id, IGluonSession cityConnection) { lock (Lots) { if (AwaitingShutdown) { return(null); } if (Lots.Values.Count >= Config.Max_Lots) { //No room return(null); } if (Lots.ContainsKey(id)) { return(null); } var ctnr = Kernel.Get <LotHostEntry>(); var bind = Kernel.GetBindings(typeof(LotHostEntry)); ctnr.CityConnection = cityConnection; Lots.Add(id, ctnr); CityConnections.LotCount = (short)Lots.Count; return(ctnr); } }
/// <summary> /// Checkes whether a binding exists for a given target on the specified kernel. /// </summary> /// <param name="kernel">The kernel.</param> /// <param name="context">The context.</param> /// <param name="target">The target.</param> /// <returns>Whether a binding exists for the target in the given context.</returns> protected virtual bool BindingExists(IKernel kernel, IContext context, ITarget target) { var targetType = this.GetTargetType(target); var request = context.Request.CreateChild(targetType, context, target); return(kernel.GetBindings(targetType).Any(b => !b.IsImplicit && b.Matches(request)) || target.HasDefaultValue); }
/// <summary> /// Creates an instance of a validator with the given type using ninject. /// </summary> /// <param name="validatorType">Type of the validator.</param> /// <returns>The newly created validator</returns> public override IValidator CreateInstance(Type validatorType) { if (!kernel.GetBindings(validatorType).Any()) { return(null); } return(kernel.Get(validatorType) as IValidator); }
public static void Register <T>(T obj) { Kernel.GetBindings(obj.GetType()) .ToList() .ForEach(binding => Kernel.RemoveBinding(binding)); Kernel.Bind <T>().ToConstant(obj); }
private static void RemoveExistingBinding(Type serviceType) { //if (kernel.TryGet(serviceType) != null) kernel.GetBindings(serviceType) .Where(binding => !binding.IsConditional) .ToList() .ForEach(b => kernel.RemoveBinding(b)); }
/// <summary> /// Adds the an instance to the dependencies. /// </summary> /// <param name="serviceType">Type of the service to add.</param> /// <param name="instance">The instance of the service to add.</param> /// <param name="lifetime">The lifetime for the registration.</param> protected override void AddDependencyInstanceCore(Type serviceType, object instance, DependencyLifetime lifetime) { if (lifetime == DependencyLifetime.Transient) { return; } var binding = _kernel.GetBindings(serviceType).FirstOrDefault(); bool foundExistingBinding = (binding != null); if (binding == null) { binding = CreateBinding(serviceType, lifetime); _kernel.AddBinding(binding); } var builder = new BindingBuilder <object>(binding, _kernel); if (lifetime == DependencyLifetime.PerRequest) { if (foundExistingBinding && binding.Target != BindingTarget.Method) { // A binding exists, but wasn't specified as an instance callback. Error! throw new DependencyResolutionException("Cannot register an instance for a type already registered"); } var store = GetStore(); var key = serviceType.GetKey(); store[key] = instance; if (!foundExistingBinding) { store.GetContextInstances().Add(new ContextStoreDependency(key, instance, new ContextStoreDependencyCleaner(_kernel))); } builder.ToMethod(c => { var ctxStore = GetStore(); return(ctxStore[serviceType.GetKey()]); }); } else if (lifetime == DependencyLifetime.Singleton) { builder.ToConstant(instance).InSingletonScope(); } }
private static IList <Type> FindTypes <T>(IKernel kernel, Func <Type, bool> filter) { return(kernel.GetBindings(typeof(T)) .Select(x => x.Service) .Distinct() .Where(filter) .ToList()); }
IEnumerable <IExport <object> > IExportProvider.GetExports(Type contractType, [CanBeNull] string?contractName) { var bindings = _kernel.GetBindings(contractType) .Where(binding => binding.Metadata.Name == contractName); var result = bindings.Select(binding => new ExportAdapter <object>(() => GetExportedValue(binding), binding.Metadata.Get <IMetadata>(ExportMetadataKey))); return(result.ToList()); }
private IMyService CreateService() { if (_kernel.GetBindings(typeof(IServiceLogger)).Any()) { return(_kernel.Get <IMyService>(new ConstructorArgument("logger", _kernel.Get <IServiceLogger>()))); } return(_kernel.Get <IMyService>()); }
public static IBindingToSyntax <T> Bind <T>() { if (s_Kernel.GetBindings(typeof(T)).Any()) { throw new InvalidOperationException(String.Format("Binding already exists for type [{0}]", typeof(T))); } return(s_Kernel.Bind <T>()); }
public override IValidator CreateInstance(Type validatorType) { var bindings = (List <IBinding>)_kernel.GetBindings(validatorType); if (bindings.Count > 0) { return((IValidator)_kernel.Get(validatorType)); } return(null); }
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { lock (bindingLock) { if (!kernel.GetBindings(controllerType).Any()) { kernel.Bind(controllerType).To(controllerType); } } return((IController)kernel.Get(controllerType)); }
public bool HasBindingFor(Type type) { IEnumerable <IBinding> bindings; #if (NET461) bindings = Kernel.GetBindings(type); #else bindings = ((IKernelConfiguration)Kernel).GetBindings(type); #endif return(bindings.Count() != 0); }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Bind<DbContext>().To<UniversityDbContext>().InRequestScope(); kernel.Bind(typeof(IRepository<>)).To(typeof(EfRepository<>)); kernel.Bind(typeof(IRepository<,>)).To(typeof(EfRepository<,>)); var h = kernel.GetBindings(typeof(IRepository<>)); kernel.Bind(b => b.From("UniversityStudentSystem.Services").SelectAllClasses().BindDefaultInterfaces()); }
public bool HasBinding(Type type, string name = null) { var bindings = kernel.GetBindings(type); if (String.IsNullOrEmpty(name)) { return(bindings.Any()); } return(bindings.Any(x => x.Metadata.Name == name)); }
/// <summary> /// Does actual binding of target type. /// </summary> /// <param name="kernel">Kernel for the binding</param> /// <param name="targetType">Type that is bound</param> /// <param name="attribute">Attribute from that type that will be used for that binding</param> /// <param name="activeProfiles">List of active profiles or null if no profiles mode</param> protected virtual void DoBinding(IKernel kernel, Type targetType, InjectableAttribute attribute, string[] activeProfiles) { if (activeProfiles != null) { // If none of profiles match current active profiles then we don't bind that type if (attribute.Profiles != null) { bool foundMatch = false; foreach (string profile in attribute.Profiles) { if (activeProfiles.Contains(profile)) { foundMatch = true; break; } } if (!foundMatch) { return; } } // If any of excluded profiles match one of current active profiles then we don't bind that type if (attribute.ExcludeInProfiles != null) { foreach (string profile in attribute.ExcludeInProfiles) { if (activeProfiles.Contains(profile)) { return; } } } } var binding0 = !kernel.GetBindings(targetType).Any() ? kernel.Bind(targetType).To(targetType) : null; if (binding0 != null) { var binding1 = DoScopeConfiguration(attribute, binding0); if (!attribute.IgnoreDisposable && typeof(IDisposable).IsAssignableFrom(targetType)) { binding1.OnDeactivation(x => ((IDisposable)x).Dispose()); } } if (attribute.Interface == null) { return; } kernel.Bind(attribute.Interface).ToMethod(ctx => ctx.Kernel.Get(targetType)); }
public void ReplaceAssemblyLoaderWith <T>(IKernel kernel) where T : AssemblyLoader { var bindings = kernel.GetBindings(typeof(AssemblyLoader)); foreach (var binding in bindings) { kernel.RemoveBinding(binding); } kernel.Bind <AssemblyLoader>().To <T>(); }
public override IValidator CreateInstance(Type validatorType) { var bindings = kernel.GetBindings(validatorType); if (!bindings.Any()) { return(null); } else { return(kernel.Get(validatorType) as IValidator); } }
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) { if (!_kernel.GetBindings(controllerType).Any()) { _kernel.Bind(controllerType).ToSelf(); } var controller = (IHttpController)(_kernel.GetAll(controllerType).FirstOrDefault()); request.RegisterForDispose(new Release(() => _kernel.Release(controller))); return(controller); }
IEnumerable <IExport <object> > IExportProvider.GetExports(Type contractType, string?contractName) { if (contractName == string.Empty) { contractName = null; } var bindings = _kernel.GetBindings(contractType) .Where(binding => GetEffectiveContractName(binding.Metadata.Name) == contractName); var result = bindings.Select(binding => new ExportAdapter <object>(() => GetExportedValue(binding), binding.Metadata.Get <IMetadata>(ExportMetadataKey))); return(result.ToList().AsReadOnly()); }
/// <summary> /// Checkes whether a binding exists for a given target on the specified kernel. /// </summary> /// <param name="kernel">The kernel.</param> /// <param name="context">The context.</param> /// <param name="target">The target.</param> /// <returns>Whether a binding exists for the target in the given context.</returns> protected virtual bool BindingExists(IKernel kernel, IContext context, ITarget target) { var targetType = GetTargetType(target); return kernel.GetBindings(targetType).Any(b => !b.IsImplicit) || target.HasDefaultValue; }
private bool GetRegistrationInfo(IKernel kernel, Type interfaceType) { return kernel.GetBindings(interfaceType).Any(); }
private bool NoBindingsIn(IKernel kernel) { return !kernel.GetBindings(_service).Any(HasAssemblyKey); }
private bool DefaultBindingIn(IKernel kernel) { return kernel.GetBindings(_service).Any(IsServiceAssemblyBinding); }