Esempio n. 1
0
        /// <summary>
        /// 绑定一个方法
        /// </summary>
        /// <param name="method">通过这个名字可以调用方法</param>
        /// <param name="target">方法调用目标</param>
        /// <param name="methodInfo">在方法调用目标中被调用的方法</param>
        /// <returns></returns>
        public IMethodBind Bind(string method, object target, MethodInfo methodInfo)
        {
            Guard.NotEmptyOrNull(method, nameof(method));
            Guard.Requires <ArgumentNullException>(methodInfo != null);

            if (!methodInfo.IsStatic)
            {
                Guard.Requires <ArgumentNullException>(target != null);
            }

            lock (syncRoot)
            {
                if (methodMappings.ContainsKey(method))
                {
                    throw new LogicException($"Method [{method}] is already {nameof(Bind)}");
                }

                var methodBind = new MethodBind(this, container, method, target, methodInfo);
                methodMappings[method] = methodBind;

                if (target == null)
                {
                    return(methodBind);
                }

                if (!targetToMethodsMappings.TryGetValue(target, out List <string> targetMappings))
                {
                    targetToMethodsMappings[target] = targetMappings = new List <string>();
                }

                targetMappings.Add(method);
                return(methodBind);
            }
        }
        /// <summary>
        /// 解除绑定
        /// </summary>
        /// <param name="methodBind">方法绑定</param>
        internal void Unbind(MethodBind methodBind)
        {
            lock (syncRoot)
            {
                methodMappings.Remove(methodBind.Service);

                if (methodBind.Target == null)
                {
                    return;
                }

                List <string> methods;
                if (!targetToMethodsMappings.TryGetValue(methodBind.Target, out methods))
                {
                    return;
                }

                methods.Remove(methodBind.Service);

                if (methods.Count <= 0)
                {
                    targetToMethodsMappings.Remove(methodBind.Target);
                }
            }
        }