Ejemplo n.º 1
0
        public static IServiceCollection AddMessageHandlers(this IServiceCollection services, Assembly assembly)
        {
            var assemblyTypes = assembly.GetTypes();

            foreach (var type in assemblyTypes)
            {
                var typeInterfaces = type.GetInterfaces();

                var handlerInterfaces = typeInterfaces
                                        .Where(Utils.IsHandlerInterface)
                                        .ToList();
                if (handlerInterfaces.Count > 0)
                {
                    var handlerFactory = new HandlerFactory(type);
                    foreach (var interfaceType in handlerInterfaces)
                    {
                        services.AddTransient(interfaceType, provider => handlerFactory.Create(provider, interfaceType));
                    }
                }

                if (typeInterfaces.Any(Utils.IsEventHandlerInterface))
                {
                    services.AddTransient(type);
                }
            }

            return(services);
        }
Ejemplo n.º 2
0
        public void AddComponent(string key, Type serviceType, Type classType, LifestyleType lifestyle, bool overwriteLifestyle)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (serviceType == null)
            {
                throw new ArgumentNullException("serviceType");
            }
            if (classType == null)
            {
                throw new ArgumentNullException("classType");
            }
            if (LifestyleType.Undefined == lifestyle)
            {
                throw new ArgumentException("The specified lifestyle must be Thread, Transient, or Singleton.", "lifestyle");
            }
            var model = ComponentModelBuilder.BuildModel(new ComponentName(key, true), new[] { serviceType }, classType, null);

            if (overwriteLifestyle || LifestyleType.Undefined == model.LifestyleType)
            {
                model.LifestyleType = lifestyle;
            }

            RaiseComponentModelCreated(model);

            var handler = HandlerFactory.Create(model);

            RegisterHandler(key, handler);
        }
Ejemplo n.º 3
0
        public virtual void AddComponentWithExtendedProperties(String key, Type serviceType, Type classType, IDictionary extendedProperties)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (extendedProperties == null)
            {
                throw new ArgumentNullException("extendedProperties");
            }
            if (serviceType == null)
            {
                throw new ArgumentNullException("serviceType");
            }
            if (classType == null)
            {
                throw new ArgumentNullException("classType");
            }

            var model = ComponentModelBuilder.BuildModel(new ComponentName(key, true), new[] { serviceType }, classType, extendedProperties);

            RaiseComponentModelCreated(model);
            var handler = HandlerFactory.Create(model);

            RegisterHandler(key, handler);
        }
Ejemplo n.º 4
0
        public void AddComponentInstance(string key, Type serviceType, Type classType, object instance)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (serviceType == null)
            {
                throw new ArgumentNullException("serviceType");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (classType == null)
            {
                throw new ArgumentNullException("classType");
            }

            var model = new ComponentModel(new ComponentName(key, true), new[] { serviceType }, classType, new Arguments {
                { "instance", instance }
            })
            {
                LifestyleType            = LifestyleType.Singleton,
                CustomComponentActivator = typeof(ExternalInstanceActivator)
            };

            RaiseComponentModelCreated(model);
            var handler = HandlerFactory.Create(model);

            RegisterHandler(key, handler);
        }
Ejemplo n.º 5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="serviceType"></param>
        /// <param name="classType"></param>
        /// <param name="parameters"></param>
        public virtual void AddComponentWithProperties(String key, Type serviceType, Type classType, IDictionary parameters)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (serviceType == null)
            {
                throw new ArgumentNullException("serviceType");
            }
            if (classType == null)
            {
                throw new ArgumentNullException("classType");
            }

            ComponentModel model = ComponentModelBuilder.BuildModel(key, serviceType, classType, parameters);

            RaiseComponentModelCreated(model);
            IHandler handler = HandlerFactory.Create(model);

            RegisterHandler(key, handler);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Used mostly by facilities. Adds an instance
        /// to be used as a component.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="serviceType"></param>
        /// <param name="instance"></param>
        public void AddComponentInstance(String key, Type serviceType, object instance)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (serviceType == null)
            {
                throw new ArgumentNullException("serviceType");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            Type classType = instance.GetType();

            ComponentModel model = new ComponentModel(key, serviceType, classType);

            model.CustomComponentActivator       = typeof(ExternalInstanceActivator);
            model.ExtendedProperties["instance"] = instance;

            RaiseComponentModelCreated(model);
            IHandler handler = HandlerFactory.Create(model);

            RegisterHandler(key, handler);
        }
        public void should_throw_if_type_not_found()
        {
            var factory = new HandlerFactory();

            factory.Register(typeof(TypeA)).Register(typeof(TypeB));

            Assert.Throws <InvalidOperationException>(() => factory.Create("NotExistedType"));
        }
    private static Action <MemoryStream, object> CreateWriteDelegate <T>()
    {
        var handler = HandlerFactory.Create <T>();

        return(delegate(MemoryStream s, object value)
        {
            handler.Write(s, (T)value);
        });
    }
Ejemplo n.º 9
0
        IHandler IKernelInternal.CreateHandler(ComponentModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            RaiseComponentModelCreated(model);
            return(HandlerFactory.Create(model));
        }
Ejemplo n.º 10
0
        public virtual IHandler AddCustomComponent(ComponentModel model, bool isMetaHandler)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            RaiseComponentModelCreated(model);
            return(HandlerFactory.Create(model, isMetaHandler));
        }
        public void should_create_instance_of_named_type_case_insensitively()
        {
            var factory = new HandlerFactory();

            factory.Register(typeof(TypeA)).Register(typeof(TypeB));

            object instance = factory.Create(typeof(TypeA).FullName.ToLowerInvariant());

            Assert.Equal(typeof(TypeA), instance);
        }
Ejemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="model"></param>
        public virtual void AddCustomComponent(ComponentModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            RaiseComponentModelCreated(model);
            IHandler handler = HandlerFactory.Create(model);

            RegisterHandler(model.Name, handler);
        }
        public static IServiceCollection AddMessageHandlers(this IServiceCollection services)
        {
            services.AddScoped <Dispatcher>();

            var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes();

            foreach (var type in assemblyTypes)
            {
                var handlerInterfaces = type.GetInterfaces()
                                        .Where(Utils.IsHandlerInterface)
                                        .ToList();

                if (!handlerInterfaces.Any())
                {
                    continue;
                }

                var handlerFactory = new HandlerFactory(type);
                foreach (var interfaceType in handlerInterfaces)
                {
                    services.AddTransient(interfaceType, provider => handlerFactory.Create(provider, interfaceType));
                }
            }

            var aggregateRootTypes = typeof(AggregateRoot <>).Assembly.GetTypes().Where(x => x.BaseType == typeof(AggregateRoot <Guid>)).ToList();

            var genericHandlerTypes = new[]
            {
                typeof(GetEntititesQueryHandler <>),
                typeof(GetEntityByIdQueryHandler <>),
                typeof(AddOrUpdateEntityCommandHandler <>),
                typeof(DeleteEntityCommandHandler <>),
            };

            foreach (var aggregateRootType in aggregateRootTypes)
            {
                foreach (var genericHandlerType in genericHandlerTypes)
                {
                    var handlerType       = genericHandlerType.MakeGenericType(aggregateRootType);
                    var handlerInterfaces = handlerType.GetInterfaces();

                    var handlerFactory = new HandlerFactory(handlerType);
                    foreach (var interfaceType in handlerInterfaces)
                    {
                        services.AddTransient(interfaceType, provider => handlerFactory.Create(provider, interfaceType));
                    }
                }
            }

            return(services);
        }
Ejemplo n.º 14
0
        private void Listener_OnMsgReceived(AsyncUserToken token, byte[] info)
        {
            string str = BytesUtil.ToHexString(info);

            try
            {
                RecieveMessageDecode reader  = new RecieveMessageDecode(info);
                RecieveMessage       message = reader.Read();

                StringBuilder sb = new StringBuilder();
                sb.Append("接收到数据:");
                sb.Append("\r\n");
                sb.Append(" 来源IP:" + token.Remote.Address.ToString());
                sb.Append("\r\n");
                sb.Append(" 接收时间:" + DateTime.Now);
                sb.Append("\r\n");
                sb.Append(" 数据类型:" + message.FunctionCode);
                sb.Append("\r\n");
                sb.Append(" 接收内容:" + str);
                sb.Append("\r\n");
                AppendLog(sb.ToString());

                //更新设备缓存
                UpdateCache(message.ClientCodeStr, token.UID);
                if (message.FunctionCode.Equals("F2"))
                {
                    return;
                }
                IMessageHandler handler = HandlerFactory.Create(message.FunctionCode, token.UID, message);
                handler.Handle();

                //如果是设备自报数据,向设备发送接收成功的报文
                if (message.FunctionCode.Equals("C0"))
                {
                    SendMessage res = new SendMessage();
                    res.ClientCode   = message.ClientCode;
                    res.CenterCode   = message.CenterCode;
                    res.SendTime     = DateTime.Now;
                    res.Serial       = 0;
                    res.FunctionCode = "C0";

                    listener.Send(token.UID, res.ToByte());
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("接收消息时出错", "接收到的消息:" + str + "\r\n" + ex.Message, ex.StackTrace);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 找尋備份處理器
        /// </summary>
        /// <param name="candidate"></param>
        /// <returns>處理器的 interface</returns>
        private List <IHandler> FindHandlers(Candidate candidate)
        {
            List <IHandler> handlers = new List <IHandler>
            {
                HandlerFactory.Create("file")
            };

            foreach (string handler in candidate.Config.Handlers)
            {
                handlers.Add(HandlerFactory.Create(handler));
            }

            handlers.Add(HandlerFactory.Create(candidate.Config.Destination));
            return(handlers);
        }
Ejemplo n.º 16
0
        public virtual void AddComponent(String key, Type classType)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (classType == null)
            {
                throw new ArgumentNullException("classType");
            }

            ComponentModel model = ComponentModelBuilder.BuildModel(key, classType, classType, null);

            RaiseComponentModelCreated(model);
            IHandler handler = HandlerFactory.Create(model);

            RegisterHandler(key, handler);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 找到檔案的所有 handlers
        /// </summary>
        /// <param name="candidate">Candidate 物件</param>
        /// <returns>Handler 陣列</returns>
        private List <Handler> FindHandlers(Candidate candidate)
        {
            // 加入 處理檔案
            List <Handler> handlers = new List <Handler>
            {
                HandlerFactory.Create("file")
            };

            // 加入 config.json 內設定的 handler
            foreach (string handler in candidate.Config.Handlers)
            {
                handlers.Add(HandlerFactory.Create(handler));
            }

            // 加入 處理檔案儲存目的
            handlers.Add(HandlerFactory.Create(candidate.Config.Destination));

            return(handlers);
        }
Ejemplo n.º 18
0
        // NOTE: this is from IKernelInternal
        public virtual void AddCustomComponent(ComponentModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            RaiseComponentModelCreated(model);
            var handler = HandlerFactory.Create(model);

            var skipRegistration = model.ExtendedProperties[ComponentModel.SkipRegistration];

            if (skipRegistration != null)
            {
                RegisterHandler(model.Name, handler, (bool)skipRegistration);
            }
            else
            {
                RegisterHandler(model.Name, handler);
            }
        }
Ejemplo n.º 19
0
 public IConnectableObservable <Event> Receive()
 {
     return(Observable.Create <Event>(async(subject, cancellationToken) =>
     {
         while (!cancellationToken.IsCancellationRequested)
         {
             try
             {
                 var bytes = await CommunicationInterface.ReadAsync(cancellationToken);
                 var handler = HandlerFactory.Create();
                 var context = new ReceiveContext(subject, bytes);
                 handler.Handle(context);
             }
             catch (Exception exception)
             {
                 subject.OnNext(new ErrorEvent(exception));
             }
         }
     })
            .Publish());
 }
Ejemplo n.º 20
0
        /// <summary>
        /// 根據檔案類型,建立處理方式
        /// </summary>
        /// <param name="candidate">檔案資訊</param>
        /// <returns>檔案將進行的處理方式</returns>
        private List <IHandler> FindHandlers(Candidate candidate)
        {
            List <IHandler> handles = new List <IHandler>();

            /// 讀取檔案
            handles.Add(HandlerFactory.Create("file"));

            /// 檔案處理
            for (int i = 0; i < candidate.Config.Handlers.Length; i++)
            {
                handles.Add(HandlerFactory.Create(candidate.Config.Handlers[i]));
            }

            /// 目錄備份
            if (!string.IsNullOrEmpty(candidate.Config.Destination))
            {
                handles.Add(HandlerFactory.Create("directory"));
            }

            return(handles);
        }
 public void Test_傳入file_回傳FileHandler物件()
 {
     // assert
     Assert.IsType <FileHandler>(HandlerFactory.Create("file"));
 }
 public void Test_傳入尚未設定的key_丟出exception()
 {
     // assert
     Assert.Throws <KeyNotFoundException>(() => HandlerFactory.Create("xxx"));
 }
 public void Test_傳入zip_回傳ZipHandler物件()
 {
     // assert
     Assert.IsType <ZipHandler>(HandlerFactory.Create("zip"));
 }
 public void Test_傳入encode_回傳EncodeHandler物件()
 {
     // assert
     Assert.IsType <EncodeHandler>(HandlerFactory.Create("encode"));
 }
 public void Test_傳入directory_回傳DirectoryHandler物件()
 {
     // assert
     Assert.IsType <DirectoryHandler>(HandlerFactory.Create("directory"));
 }