Example #1
0
        public bool Matches(BindingKey routingKey)
        {
            if (BindingKey.IsEmpty)
            {
                return(true);
            }

            if (routingKey.IsJoined && BindingKey.PartCount != 1)
            {
                return(MatchesJoinedRoutingKey(routingKey.GetPart(0)));
            }

            for (var i = 0; i < routingKey.PartCount; i++)
            {
                var evaluatedPart = BindingKey.GetPart(i);
                if (evaluatedPart == "#")
                {
                    return(true);
                }

                if (evaluatedPart != "*" && routingKey.GetPart(i) != evaluatedPart)
                {
                    return(false);
                }
            }

            return(routingKey.PartCount == BindingKey.PartCount);
        }
Example #2
0
        public void ShouldMatchSubscription()
        {
            var allowed = new DatabaseStatus()
            {
                DatacenterName = "Paris",
                FailureType    = "Oh no!"
            };

            var notAllowed = new DatabaseStatus()
            {
                DatacenterName = "London",
                FailureType    = "Oh no!"
            };

            var key = BindingKey.Create(allowed);

            var subscription = Subscription.Matching <DatabaseStatus>(x => x.DatacenterName == "Paris");

            var allowedMessageBinding    = MessageBinding.FromMessage(allowed);
            var notAllowedMessageBinding = MessageBinding.FromMessage(notAllowed);

            Assert.IsTrue(subscription.Matches(allowedMessageBinding));

            Assert.IsFalse(subscription.Matches(notAllowedMessageBinding));
        }
Example #3
0
        public void TestGetWithMember_Equals_HashCode()
        {
            BindingKey b1  = BindingKey.Get(typeof(object));
            BindingKey b1i = BindingKey.GetMember(typeof(object));
            BindingKey b2i = BindingKey.GetMember <object>();

            Assert.AreEqual(true, b1i.IsMember);
            Assert.AreEqual(true, b2i.IsMember);
            Assert.AreEqual(null, b1i.Qualifier);
            Assert.AreEqual(null, b2i.Qualifier);

            Assert.AreEqual(b1i, b2i);
            Assert.AreEqual(b1i.GetHashCode(), b2i.GetHashCode());
            Assert.AreNotEqual(b1, b1i);
            Assert.AreNotEqual(b1.GetHashCode(), b1i.GetHashCode());

            BindingKey b1Ex  = BindingKey.Get(typeof(Exception));
            BindingKey b1Exi = BindingKey.GetMember(typeof(Exception));
            BindingKey b2Exi = BindingKey.GetMember <Exception>();

            Assert.AreEqual(b1Exi, b2Exi);
            Assert.AreEqual(b1Exi.GetHashCode(), b2Exi.GetHashCode());
            Assert.AreNotEqual(b1Ex.GetHashCode(), b1Exi.GetHashCode());

            Assert.AreNotEqual(b1i, b1Exi);
            Assert.AreNotEqual(b2i, b2Exi);
        }
		private BindingKey ResolveBindingForGeneric(BindingKey explicitKey, Type bindingType) {
			var genericBindingKey = BindingKey.Get (bindingType.GetGenericTypeDefinition (), explicitKey.Qualifier);
			var genericBindingType = bindingType.GetGenericTypeDefinition ();
			var genericTypeArguments = bindingType.GetGenericArguments ();

			IBindingConfig genericBindingConfig;
			Type genericConcreteType = GetGenericImplementation (genericBindingKey, genericBindingType, out genericBindingConfig);

			// Have 'implementedBy OR explicit binding'
			if (genericConcreteType != null) {
				OpenGenericBinding.For (genericBindingType).To (genericConcreteType); // validate binding
				Type concreteType = genericConcreteType.MakeGenericType (genericTypeArguments);

				var binding = new GenericBinding () {
					BindingConfig = new BindingConfig(concreteType),
					BindingKey = explicitKey.ToImplicit(),
					ConcreteType = concreteType
				};

				if (genericBindingConfig != null) {
					binding.BindingConfig.Lifestyle = genericBindingConfig.Lifestyle;
				}

				injector.Register (binding);

				return binding.BindingKey;
			}

			return null;
		}
Example #5
0
 internal void AssertValid()
 {
     if (BindingKey.IsEmpty() || QueueName.IsEmpty() || ExchangeName.IsEmpty())
     {
         throw new InvalidOperationException($"{nameof(BindingKey)} properties {nameof(BindingKey)}, {nameof(QueueName)}, and {nameof(ExchangeName)} are all required for this operation");
     }
 }
Example #6
0
            public void Accept(PeerCollector peerCollector, BindingKey routingKey)
            {
                if (IsLeaf(routingKey) || _matchesAll)
                {
                    peerCollector.Offer(_peers);
                    return;
                }

                _sharpNode?.Accept(peerCollector, routingKey);
                _starNode?.Accept(peerCollector, routingKey);

                var nextPart = routingKey.GetPart(_nextPartIndex);

                if (nextPart == null)
                {
                    return;
                }

                if (_childrenNodes == null)
                {
                    return;
                }

                SubscriptionNode childNode;

                if (_childrenNodes.TryGetValue(nextPart, out childNode))
                {
                    childNode.Accept(peerCollector, routingKey);
                }
            }
        /// <summary>
        /// Adds the implicit types.
        /// </summary>
        /// <param name="bindingKey">Binding key.</param>
        /// <param name="implicitTypeKeys">Implicit type keys.</param>
        private void AddImplicitTypes(BindingKey bindingKey, SetShim <BindingKey> implicitTypeKeys)
        {
            foreach (BindingKey implicitTypeKey in implicitTypeKeys)
            {
                if (BindingAttributeUtils.GetImplementedBy(implicitTypeKey.BindingType) == null)
                {
                    SetShim <BindingKey> newSet, oldSet;

                    if (implicitTypeLookup.TryGetValue(implicitTypeKey, out oldSet))
                    {
                        implicitTypeLookup.Remove(implicitTypeKey);
                        newSet = new SetShim <BindingKey> (oldSet);
                    }
                    else
                    {
                        newSet = new SetShim <BindingKey> ();
                    }

                    newSet.Add(bindingKey);
                    implicitTypeLookup.Add(implicitTypeKey, newSet);
                }
                else
                {
                    return;                     // TODO - should skip rest?
                }
            }
        }
        public void should_match_joined_qpid_message_without_machine_name()
        {
            var bindingKey   = BindingKey.Joined(".Abc.Foo.0");
            var subscription = Subscription.Matching <InstanceHeartBeat>(x => x.InstanceName == "Abc.Foo.0");

            subscription.Matches(bindingKey).ShouldBeTrue();
        }
Example #9
0
 private void UpdatePeerSubscription(Peer peer, BindingKey subscription, UpdateAction action)
 {
     if (subscription.IsEmpty)
         UpdatePeersMatchingAllMessages(peer, action);
     else
         _rootNode.Update(peer, subscription, action);
 }
Example #10
0
        public void TestGetWithQualifer_Equals_HashCode()
        {
            BindingKey b1  = BindingKey.Get(typeof(object));
            BindingKey b1q = BindingKey.Get(typeof(object), "foo");
            BindingKey b2q = BindingKey.Get <object>("foo");

            Assert.AreEqual(false, b1q.IsMember);
            Assert.AreEqual(false, b2q.IsMember);
            Assert.AreEqual("foo", b1q.Qualifier);
            Assert.AreEqual("foo", b2q.Qualifier);

            Assert.AreEqual(b1q, b2q);
            Assert.AreEqual(b1q.GetHashCode(), b2q.GetHashCode());
            Assert.AreNotEqual(b1, b1q);
            Assert.AreNotEqual(b1.GetHashCode(), b1q.GetHashCode());

            BindingKey b1Ex  = BindingKey.Get(typeof(Exception));
            BindingKey b1Exq = BindingKey.Get(typeof(Exception), "foo");
            BindingKey b2Exq = BindingKey.Get <Exception>("foo");

            Assert.AreEqual(b1Exq, b2Exq);
            Assert.AreEqual(b1Exq.GetHashCode(), b2Exq.GetHashCode());
            Assert.AreNotEqual(b1Ex.GetHashCode(), b1Exq.GetHashCode());

            Assert.AreNotEqual(b1q, b1Exq);
            Assert.AreNotEqual(b2q, b2Exq);
        }
        public object Get(Type service, string name = null, params IIocParameter[] parameters)
        {
            this.NotBeDisposed();
            Should.NotBeNull(service, nameof(service));
            var key = new BindingKey(service, name);
            BindingRegistration registration = null;

            lock (_bindingRegistrations)
            {
                List <BindingRegistration> list;
                if (_bindingRegistrations.TryGetValue(key, out list))
                {
                    if (list.Count > 1)
                    {
                        throw new InvalidOperationException($"Cannot activate type {service} found more that one binding");
                    }
                    if (list.Count == 1)
                    {
                        registration = list[0];
                    }
                }
            }
            if (registration != null)
            {
                return(registration.Resolve(parameters));
            }
            if (_parent != null && _parent.HasRegistration(key))
            {
                return(_parent.Get(service, name, parameters));
            }
            return(Resolve(service, parameters));
        }
        private IList <object> GetAll(Type service, string name = null, params IIocParameter[] parameters)
        {
            Should.NotBeNull(service, nameof(service));
            var key = new BindingKey(service, name);
            List <BindingRegistration> registrations;

            lock (_bindingRegistrations)
                _bindingRegistrations.TryGetValue(key, out registrations);
            if (registrations != null && registrations.Count > 0)
            {
                var result = new object[registrations.Count];
                for (int i = 0; i < registrations.Count; i++)
                {
                    result[i] = registrations[i].Resolve(parameters);
                }
                return(result);
            }
            if (_parent != null && _parent.HasRegistration(key))
            {
                return(_parent.GetAll(service, name, parameters));
            }

            object value;

            if (TryResolve(service, parameters, out value))
            {
                return new[] { value }
            }
            ;
            return(Empty.Array <object>());
        }
Example #13
0
        public void should_create_subscription_by_example()
        {
            var subscription = Subscription.ByExample(x => new FakeRoutableCommand(12, "name"));

            subscription.MessageTypeId.ShouldEqual(new MessageTypeId(typeof(FakeRoutableCommand)));
            subscription.BindingKey.ShouldEqual(BindingKey.Split("12.name.*"));
        }
Example #14
0
        public void should_create_subscription_by_example_with_placeholder()
        {
            var subscription = Subscription.ByExample(x => new FakeRoutableCommand(x.Any <decimal>(), "name"));

            subscription.MessageTypeId.ShouldEqual(new MessageTypeId(typeof(FakeRoutableCommand)));
            subscription.BindingKey.ShouldEqual(BindingKey.Split("*.name.*"));
        }
Example #15
0
            public int Update(Peer peer, BindingKey subscription, UpdateAction action)
            {
                if (IsLeaf(subscription))
                {
                    var update = UpdateList(peer, action);
                    _peerCountIncludingChildren += update;

                    return(update);
                }

                var nextPart = subscription.GetPart(_nextPartIndex);

                if (subscription.IsSharp(_nextPartIndex) || nextPart == null)
                {
                    return(UpdateChildNode(GetOrCreateSharpNode(), peer, subscription, action, null, _removeSharpNode));
                }

                if (subscription.IsStar(_nextPartIndex))
                {
                    return(UpdateChildNode(GetOrCreateStarNode(), peer, subscription, action, null, _removeStarNode));
                }

                var childNode = GetOrAddChildNode(nextPart);

                return(UpdateChildNode(childNode, peer, subscription, action, nextPart, _removeNode));
            }
Example #16
0
        public Injector()
        {
            // Registration of resolvers
            allResolvers = new SafeDictionary <BindingKey, IResolver>(syncLock);

            // Registration of binding key resolvers
            implicitBindingResolver = new ImplicitBindingResolver(syncLock);
            genericBindingRresolver = new GenericBindingResolver(this, syncLock);

            // Init resolvers cache
            instanceResolversCache = new SafeDictionary <Type, IResolver>(syncLock);

            // Init resolver
            Expression <Action> tmpExpr = () => CreateResolverInstance <Exception, Exception>(null, null);

            createResolverInstanceGeneric = ((MethodCallExpression)tmpExpr.Body).Method.GetGenericMethodDefinition();

            // Init bindExplicit
            Expression <Action> tmpBindExpr = () => BindExplicit <Exception, Exception> (null, null);

            bindExplicitGeneric = ((MethodCallExpression)tmpBindExpr.Body).Method.GetGenericMethodDefinition();

            // Implicitly resolvable
            Expression <Func <Injector> > injectorFactoryExpr = () => this;
            var bindingConfig = new BindingConfig(typeof(Injector));

            bindingConfig.FactoryExpression = injectorFactoryExpr;
            bindingConfig.Lifestyle         = Lifestyle.Singleton;
            var injectorResolver = BindExplicit <Injector, Injector>(BindingKey.Get(typeof(Injector)), bindingConfig);
        }
Example #17
0
        private IResolver BindExplicit <BType, CType>(BindingKey bindingKey, IBindingConfig bindingConfig)
            where BType : class
            where CType : class, BType
        {
            lock (syncLock) {
                IResolver oldResolver;
                if (allResolvers.TryGetValue(bindingKey, out oldResolver))
                {
                    if (bindingKey.IsImplicit)
                    {
                        // Handle edge case where 2 thread auto-register same implicit
                        // binding via 'ResolveBinding'. More complex to add guard within
                        // ResolveBinding() than here.
                        return(oldResolver);
                    }
                    allResolvers.Remove(bindingKey);
                }

                // Add after create resolver
                var resolver = CreateResolverInstance <BType, CType> (bindingKey, bindingConfig);

                // Register Implicits
                implicitBindingResolver.Register(bindingKey);

                return(resolver);
            }
        }
Example #18
0
        public IList <Peer> GetPeers(BindingKey routingKey)
        {
            var peerCollector = new PeerCollector(_peersMatchingAllMessages);

            _rootNode.Accept(peerCollector, routingKey);

            return(peerCollector.GetPeers());
        }
Example #19
0
        /// <inheritdoc/>
        public T InjectMembers <T> (T instance)
            where T : class
        {
            var iResolver = ResolveResolver(BindingKey.GetMember(instance.GetType()));

            iResolver.DoInject(instance);
            return(instance);
        }
        public void should_match_joined_routing_key_with_splitted_token_subscription_and_wildcard_2()
        {
            var subscription = new Subscription(MessageUtil.TypeId <FakeRoutableCommand>(), new BindingKey("Abc", "#"));

            var routingKey = BindingKey.Joined("Abc.Service.42");

            subscription.Matches(routingKey).ShouldBeTrue();
        }
Example #21
0
        public IList<Peer> GetPeers(BindingKey routingKey)
        {
            var peerCollector = new PeerCollector(_peersMatchingAllMessages);

            _rootNode.Accept(peerCollector, routingKey);

            return peerCollector.GetPeers();
        }
 /// <summary>
 /// Register the specified binding.
 /// </summary>
 /// <param name="binding">Binding.</param>
 internal void Register(BindingKey bindingKey)
 {
     if (!bindingKey.IsMember && !bindingKey.IsImplicit)
     {
         implicitTypeLookup.Remove(bindingKey);
         AddImplicitTypes(bindingKey, GetImplicitTypes(bindingKey));
     }
 }
        public void should_not_match_invalid_joined_routing_key_with_splitted_token_subscription()
        {
            var subscription = new Subscription(MessageUtil.TypeId <FakeRoutableCommand>(), new BindingKey("Abc", "Service", "0"));

            var routingKey = BindingKey.Joined("Abc.Service.1");

            subscription.Matches(routingKey).ShouldBeFalse();
        }
Example #24
0
            private bool IsLeaf(BindingKey bindingKey)
            {
                if (_nextPartIndex == 0)
                {
                    return(false);
                }

                return(_nextPartIndex == bindingKey.PartCount);
            }
        internal BoundOpenGenericBinding(Type bindingType, Type concreteType)
        {
            ValidateGenericType(bindingType);
            ValidateGenericType(concreteType);

            BindingConfig = new BindingConfig(concreteType);
            BindingKey    = BindingKey.Get(bindingType);
            ConcreteType  = concreteType;
        }
Example #26
0
        public IList<Peer> GetPeers(BindingKey routingKey)
        {
            if (_dynamicPeerSubscriptions.Count == 0)
                return _peersHandlingAllMessages;

            return _peersHandlingAllMessages
                .Concat(_dynamicPeerSubscriptions.Where(x => x.Subscription.Matches(routingKey)).Select(i => i.Peer))
                .DistinctBy(i => i.Id)
                .ToList();
        }
Example #27
0
        public void RemoveBinding <TTarget>(Expression <Func <TTarget> > target)
        {
            var      key = new BindingKey(target.MemberInfo());
            IBinding binding;

            if (Bindings.Value.TryRemove(key, out binding))
            {
                binding.Dispose();
            }
        }
Example #28
0
 private IResolver CreateResolverInstanceGeneric(BindingKey bindingKey, Type implType)
 {
     try {
         return((IResolver)createResolverInstanceGeneric
                .MakeGenericMethod(bindingKey.BindingType, implType)
                .Invoke(this, new object[] { bindingKey, null }));
     } catch (TargetInvocationException ex) {
         throw ex.InnerException;
     }
 }
Example #29
0
        public void should_send_routing_key_exception()
        {
            var msg = new FakeRoutableCommand(0, null);

            var exception = Assert.Throws <InvalidOperationException>(() => BindingKey.Create(msg));

            exception.Message.ShouldContain(typeof(FakeRoutableCommand).Name);
            exception.Message.ShouldContain("Name");
            exception.Message.ShouldContain("can not be null");
        }
Example #30
0
 private void UpdatePeerSubscription(Peer peer, BindingKey subscription, UpdateAction action)
 {
     if (subscription.IsEmpty)
     {
         UpdatePeersMatchingAllMessages(peer, action);
     }
     else
     {
         _rootNode.Update(peer, subscription, action);
     }
 }
Example #31
0
        /// <summary>
        /// Resolves the implicit key.
        /// </summary>
        /// <returns>The implicit key.</returns>
        /// <param name="bindingKey">Binding key.</param>
        private BindingKey ResolveImplicitKey(BindingKey bindingKey)
        {
            BindingKey implicitKey = genericBindingRresolver.ResolveBinding(bindingKey);

            if (implicitKey == null)
            {
                implicitKey = implicitBindingResolver.ResolveBinding(bindingKey);
            }

            return(implicitKey);
        }
		/// <summary>
		/// Gets the generic implementation.
		/// </summary>
		/// <returns>The generic implementation.</returns>
		/// <param name="genericBindingKey">Generic binding key.</param>
		/// <param name="genericBindingType">Generic binding type.</param>
		/// <param name="genericBindingConfig">Generic binding config.</param>
		private Type GetGenericImplementation (BindingKey genericBindingKey, Type genericBindingType, out IBindingConfig genericBindingConfig) {
			genericBindingConfig = null;

			// Try registrations
			if (allGenericResolvers.TryGetValue (genericBindingKey, out genericBindingConfig)) {
				return genericBindingConfig.ConcreteType;
			}

			// Try implicit
			return BindingAttributeUtils.GetImplementedBy (genericBindingType);
		}
Example #33
0
        public void UnsafeTypedGetTest()
        {
            var context = TestsFactory.BindingContext();

            context.Bind <int>().To(() => 42);

            var name = new BindingName(InnerBindingNames.Empty);
            var key  = new BindingKey(typeof(int));

            Assert.DoesNotThrow(() => context.Unsafe.TryGet(name, key, new object[0]));
        }
        private static byte[] SerializeBindingKeys(BindingKey[] bindingKeys)
        {
            using (var memoryStream = new MemoryStream())
            using (var binaryWriter = new BinaryWriter(memoryStream))
            {
                binaryWriter.Write(bindingKeys.Length);
                for (var keyIndex = 0; keyIndex < bindingKeys.Length; keyIndex++)
                {
                    var bindingKey = bindingKeys[keyIndex];
                    binaryWriter.Write(bindingKey.PartCount);

                    for (var partIndex = 0; partIndex < bindingKey.PartCount; partIndex++)
                        binaryWriter.Write(bindingKey.GetPart(partIndex));
                }
                return memoryStream.ToArray();
            }
        }
 private static BindingKey[] DeserializeBindingKeys(byte[] bindingKeysBytes)
 {
     using (var memoryStream = new MemoryStream(bindingKeysBytes))
     using (var binaryReader = new BinaryReader(memoryStream))
     {
         var bindingKeyCount = binaryReader.ReadInt32();
         var bindingKeys = new BindingKey[bindingKeyCount];
         for (var keyIndex = 0; keyIndex < bindingKeyCount; keyIndex++)
         {
             var partsCount = binaryReader.ReadInt32();
             var parts = new string[partsCount];
             
             for (var partIndex = 0; partIndex < partsCount; partIndex++)
                 parts[partIndex] = binaryReader.ReadString();
             
             bindingKeys[keyIndex] = new BindingKey(parts);
         }
         return bindingKeys;
     }
 }
Example #36
0
            public int Update(Peer peer, BindingKey subscription, UpdateAction action)
            {
                if (IsLeaf(subscription))
                {
                    var update = UpdateList(peer, action);
                    _peerCountIncludingChildren += update;

                    return update;
                }

                var nextPart = subscription.GetPart(_nextPartIndex);

                if (nextPart == "#" || nextPart == null)
                {
                    var sharpNode = GetOrCreateSharpNode();
                    return UpdateChildNode(sharpNode, peer, subscription, action, null, _removeSharpNode);
                }

                if (nextPart == "*")
                {
                    var starNode = GetOrCreateStarNode();
                    return UpdateChildNode(starNode, peer, subscription, action, null, _removeStarNode);
                }

                var childNode = GetOrAddChildNode(nextPart);
                return UpdateChildNode(childNode, peer, subscription, action, nextPart, _removeNode);
            }
Example #37
0
            public void Accept(PeerCollector peerCollector, BindingKey routingKey)
            {
                if (IsLeaf(routingKey) || _matchesAll)
                {
                    peerCollector.Offer(_peers);
                    return;
                }

                if (_sharpNode != null)
                    _sharpNode.Accept(peerCollector, routingKey);

                if (_starNode != null)
                    _starNode.Accept(peerCollector, routingKey);

                var nextPart = routingKey.GetPart(_nextPartIndex);
                if (nextPart == null)
                    return;

                if (_childrenNodes == null)
                    return;

                SubscriptionNode childNode;
                if (_childrenNodes.TryGetValue(nextPart, out childNode))
                    childNode.Accept(peerCollector, routingKey);
            }
Example #38
0
 public void Add(Peer peer, BindingKey subscription)
 {
     UpdatePeerSubscription(peer, subscription, UpdateAction.Add);
 }
Example #39
0
            private int UpdateChildNode(SubscriptionNode childNode, Peer peer, BindingKey subscription, UpdateAction action, string childNodePart, Action<SubscriptionNode, string> remover)
            {
                var update = childNode.Update(peer, subscription, action);
                _peerCountIncludingChildren += update;
                
                if (childNode.IsEmpty)
                    remover(this, childNodePart);

                return update;
            }
Example #40
0
            private bool IsLeaf(BindingKey bindingKey)
            {
                if (_nextPartIndex == 0)
                    return false;

                if (bindingKey.IsEmpty)
                    return _nextPartIndex == 1;

                return _nextPartIndex == bindingKey.PartCount;
            }
Example #41
0
 public void Remove(Peer peer, BindingKey subscription)
 {
     UpdatePeerSubscription(peer, subscription, UpdateAction.Remove);
 }
Example #42
0
        public void should_use_special_char_for_empty_binding_key()
        {
            var empty = new BindingKey(new string[0]);

            empty.ToString().ShouldEqual("#");
        }
 private void AddToGlobalSubscriptionsIndex(MessageTypeId messageTypeId, BindingKey bindingKey)
 {
     var subscriptionTree = _globalSubscriptionsIndex.GetOrAdd(messageTypeId, _ => new PeerSubscriptionTree());
     subscriptionTree.Add(Peer, bindingKey);
 }
            private void RemoveFromGlobalSubscriptionsIndex(MessageTypeId messageTypeId, BindingKey bindingKey)
            {
                var subscriptionTree = _globalSubscriptionsIndex.GetValueOrDefault(messageTypeId);
                if (subscriptionTree == null)
                    return;

                subscriptionTree.Remove(Peer, bindingKey);

                if (subscriptionTree.IsEmpty)
                    _globalSubscriptionsIndex.Remove(messageTypeId);
            }