コード例 #1
0
ファイル: EventBus.cs プロジェクト: richfuns/EventBus
        public ISubscription RegisterSubscription(object eventProxy)
        {
            if (Subscriptions.ContainsKey(eventProxy))
            {
                throw new AlreadyRegisteredException(eventProxy, this);
            }

            var methods = _handlerInfoFinder.GetPublicInstanceMethods(eventProxy);

            var handlersMethodData = _handlerInfoFinder.GetHandlersData(methods);

            var handlers = _handlerFactory.CreateHandlers(handlersMethodData, eventProxy);

            var typeAndHandler = new Dictionary <Type, List <IHandler> >();

            foreach (var handler in handlers)
            {
                if (!typeAndHandler.ContainsKey(handler.HandledType))
                {
                    typeAndHandler.Add(handler.HandledType, new List <IHandler>());
                }

                typeAndHandler[handler.HandledType].Add(handler);
            }

            var dict = new Dictionary <Type, IList <IHandler> >();

            foreach (var keyValuePair in typeAndHandler)
            {
                dict.Add(keyValuePair.Key, keyValuePair.Value);
                if (TypeToHandler.TryGetValue(keyValuePair.Key, out IHandlerCollection handlerCollect))
                {
                    handlerCollect.AddHandlers(keyValuePair.Value);
                }
                else
                {
                    var handlCollType   = typeof(HandlerCollection <>).MakeGenericType(keyValuePair.Key);
                    var handlCollection = Activator.CreateInstance(handlCollType, this) as IHandlerCollection;
                    TypeToHandler.Add(keyValuePair.Key, handlCollection);
                    handlCollection?.AddHandlers(keyValuePair.Value);
                }
            }

            var sub = new Subscription(eventProxy, this, dict);

            Subscriptions.Add(eventProxy, sub);
            return(sub);
        }