void PublishEvent() { try { while (true) { var eventContext = MessageQueue.Take(); while (true) { try { _topicClient.Send(((MessageContext)eventContext).BrokeredMessage); Task.Factory.StartNew(() => { using (var messageStore = IoCFactory.Resolve <IMessageStore>()) { messageStore.RemovePublishedEvent(eventContext.MessageID); } }); break; } catch (Exception) { Thread.Sleep(1000); } } } } catch (Exception ex) { _logger.Debug("end publish working", ex); } }
public MessageProcessor(string serviceBusConnectionString) { _serviceBusConnectionString = serviceBusConnectionString; _logger = IoCFactory.Resolve <ILoggerFactory>().Create(this.GetType()); _namespaceManager = NamespaceManager.CreateFromConnectionString(_serviceBusConnectionString); _messageFactory = MessagingFactory.CreateFromConnectionString(_serviceBusConnectionString); }
/// <summary> /// process the order. /// </summary> /// <param name="order">Order to process.</param> /// <returns>True if the operation was successful.</returns> public bool ProcessOrder(Order order) { try { order.Items = IoCFactory.Resolve <IItemsRepository>().GetItemsByCustomer(order.CustomerId); Product product = null; foreach (var itm in order.Items) { product = IoCFactory.Resolve <IProductsServiceAgent>().GetProductById(itm.ProductId).Results.FirstOrDefault(); itm.Product = product; } bool answerServiceAgent = IoCFactory.Resolve <IOrdersServiceAgent>().ProcessOrder(order); if (answerServiceAgent) { bool answerItems = IoCFactory.Resolve <IItemsRepository>().DeleteItemsByCustomerId(order.CustomerId); } return(answerServiceAgent); } catch (Exception ex) { throw new Exception("Se produjo un error al procesar la orden", ex); } }
private static void writeEvent() { ISerializer serializer = IoCFactory.Resolve <ISerializer>(); IEventPublisher eventPublisher = IoCFactory.Resolve <IEventPublisher>(); ImportLogDTO importLogDTO = new ImportLogDTO { Status = 1, DeviceId = "PRUEBA123", FileName = "PRUEBA.xml", FileType = "PRE", ImportDate = DateTime.Now, Message = "PRUEBA MESSAGE", TotalSeconds = 2, StartDate = DateTime.Now.AddMinutes(-2), EndDate = DateTime.Now }; ImportEventDTO importEventDTO = new ImportEventDTO { importLog = importLogDTO }; Event ev = new Event { Source = "UnPackerAdded", EventType = "LoadProfile", TriggeredAt = DateTime.Now, Data = serializer.Serialize(importEventDTO) }; ////Escribe el evento en la cola. eventPublisher.PublishEvent(ev); }
/// <summary> /// Get the items of a customer. /// </summary> /// <param name="customerId">Customer Id.</param> /// <param name="lstItemsSerialized">Serialized list items.</param> /// <returns>List items.</returns> public List <Item> GetItemsByCustomer(int customerId, string lstItemsSerialized) { try { List <Item> lstItems = JsonSerializer.DeserializeObject <List <Item> >(lstItemsSerialized); List <Item> itemsCurrent = IoCFactory.Resolve <IItemsRepository>().GetItemsByCustomer(customerId); foreach (var itm in lstItems) { Item item = itemsCurrent.FirstOrDefault(it => it.ProductId == itm.ProductId); if (item != null) { item.Quantity += itm.Quantity; IoCFactory.Resolve <IItemsRepository>().ModifyQuantityToItem(item); } else { IoCFactory.Resolve <IItemsRepository>().AddItem(itm, customerId); } } return(IoCFactory.Resolve <IItemsRepository>().GetItemsByCustomer(customerId)); } catch (Exception ex) { throw new Exception("Se produjo un error al consultar los items del cliente", ex); } }
/// <summary> /// 根据名称获取仓储 /// </summary> /// <typeparam name="TAggregateRoot">聚合根类型</typeparam> /// <param name="name">名称</param> /// <returns>仓储</returns> public IRepository <TAggregateRoot> GetRepository <TAggregateRoot>(string name) where TAggregateRoot : class, IAggregateRoot { IRepository repository = null; IRepository <TAggregateRoot> genericRepo = null; if (repositories.TryGetValue(typeof(IRepository <TAggregateRoot>), out repository)) { genericRepo = (IRepository <TAggregateRoot>)repository; } else { foreach (var entityRepository in EntityRepositoryMap) { if (typeof(TAggregateRoot).GetInterfaces().Contains(entityRepository.Key)) { repository = (IRepository <TAggregateRoot>)IoCFactory.Resolve(entityRepository.Value.MakeGenericType(typeof(TAggregateRoot)), name); } } if (repository == null) { repository = IoCFactory.Resolve <IRepository <TAggregateRoot> >(name); } repositories.Add(typeof(IRepository <TAggregateRoot>), repository); genericRepo = (IRepository <TAggregateRoot>)repository; genericRepo.Join(this); } return(genericRepo); }
/// <summary> /// 根据名称获取领域仓储 /// </summary> /// <param name="name">名称</param> /// <returns>仓储</returns> public IDomainRepository GetDomainRepository(string name) { var repository = IoCFactory.Resolve <IDomainRepository>(name); repository.Join(this); return(repository); }
/// <summary> /// 根据名称获取领域仓储 /// </summary> /// <typeparam name="TDomainRespository">领域仓储类型</typeparam> /// <param name="name">名称</param> /// <returns>领域仓储</returns> public IDomainRepository GetDomainRepository <TDomainRespository>(string name) where TDomainRespository : IDomainRepository { var repository = IoCFactory.Resolve <TDomainRespository>(name); repository.Join(this); return(repository); }
public void TestLog() { var loggerFactory = IoCFactory.Resolve <ILoggerFactory>(); var logger = loggerFactory.Create(nameof(Log4NetLoggerTests)); var message = "test log level"; WriteLine(logger.Level); LogTest(logger, message); logger.ChangeLogLevel(Level.Debug); Console.WriteLine(logger.Level); LogTest(logger, message); logger.ChangeLogLevel(Level.Info); Console.WriteLine(logger.Level); LogTest(logger, message); logger.ChangeLogLevel(Level.Warn); Console.WriteLine(logger.Level); LogTest(logger, message); logger.ChangeLogLevel(Level.Error); Console.WriteLine(logger.Level); LogTest(logger, message); logger.ChangeLogLevel(Level.Fatal); Console.WriteLine(logger.Level); LogTest(logger, message); }
/// <summary> /// Get order by customer id. /// </summary> /// <param name="customerId">Identifier customer.</param> /// <param name="lstProductsId">List of productIds.</param> /// <param name="lstQuantitys"></param> /// <returns>Order.</returns> public Order GetOrderByCustomerId(int customerId, string lstItemsSerialized) { try { List <Item> lstItems = JsonSerializer.DeserializeObject <List <Item> >(lstItemsSerialized); Order order = new Order() { CustomerId = customerId, Items = lstItems, OrderId = customerId, }; Product product = null; foreach (var itm in order.Items) { product = IoCFactory.Resolve <IProductsServiceAgent>().GetProductById(itm.ProductId).Results.FirstOrDefault(); itm.Product = product; } return(order); } catch (Exception ex) { throw new Exception("Se produjo un error al consultar la orden del cliente.", ex); } }
IEnumerable <IMessageContext> GetAllUnSentMessages <TMessage>() where TMessage : UnSentMessage { var messageContexts = new List <IMessageContext>(); this.Set <TMessage>().ToList().ForEach(message => { try { var rawMessage = message.MessageBody.ToJsonObject(Type.GetType(message.Type)) as IMessage; if (rawMessage != null) { var messageContext = IoCFactory.Resolve <IMessageContext>("MessageStoreMapping", new ParameterOverride("message", rawMessage)); messageContexts.Add(messageContext); } else { this.Set <TMessage>().Remove(message); _logger.ErrorFormat("get unsent message error: {0}", message.ToJson()); } } catch (Exception) { this.Set <TMessage>().Remove(message); _logger.ErrorFormat("get unsent message error: {0}", message.ToJson()); } }); SaveChanges(); return(messageContexts); }
public MessageSender(IMessageQueueClient messageQueueClient, string defaultTopic = null) { _messageQueueClient = messageQueueClient; _defaultTopic = defaultTopic; _messageQueue = new BlockingCollection <IMessageContext>(); _logger = IoCFactory.Resolve <ILoggerFactory>().Create(this.GetType()); }
public EventPublisher(string serviceBusConnectionString, string topic) { _serviceBusClient = new ServiceBusClient(serviceBusConnectionString); MessageQueue = new BlockingCollection <IMessageContext>(); _logger = IoCFactory.Resolve <ILoggerFactory>().Create(this.GetType()); _topic = topic; }
protected override void ConsumeMessage(IFramework.MessageQueue.EQueue.MessageFormat.MessageContext eventContext, EQueueProtocols.QueueMessage queueMessage) { _Logger.DebugFormat("Start Handle event , messageContextID:{0} queueID:{1}", eventContext.MessageID, queueMessage.QueueId); var message = eventContext.Message; var messageHandlerTypes = HandlerProvider.GetHandlerTypes(message.GetType()); if (messageHandlerTypes.Count == 0) { return; } messageHandlerTypes.ForEach(messageHandlerType => { PerMessageContextLifetimeManager.CurrentMessageContext = eventContext; eventContext.ToBeSentMessageContexts.Clear(); var messageStore = IoCFactory.Resolve <IMessageStore>(); var subscriptionName = string.Format("{0}.{1}", SubscribeTopic, messageHandlerType.FullName); if (!messageStore.HasEventHandled(eventContext.MessageID, subscriptionName)) { try { var messageHandler = IoCFactory.Resolve(messageHandlerType); ((dynamic)messageHandler).Handle((dynamic)message); var commandContexts = eventContext.ToBeSentMessageContexts; var eventBus = IoCFactory.Resolve <IEventBus>(); var messageContexts = new List <MessageContext>(); eventBus.GetMessages().ForEach(msg => messageContexts.Add(new MessageContext(msg))); messageStore.SaveEvent(eventContext, subscriptionName, commandContexts, messageContexts); if (commandContexts.Count > 0) { IoCFactory.Resolve <ICommandBus>().Send(commandContexts.AsEnumerable()); } if (messageContexts.Count > 0) { IoCFactory.Resolve <IEventPublisher>().Publish(messageContexts.ToArray()); } } catch (Exception e) { if (e is DomainException) { _Logger.Warn(message.ToJson(), e); } else { //IO error or sytem Crash _Logger.Error(message.ToJson(), e); } messageStore.SaveFailHandledEvent(eventContext, subscriptionName, e); } finally { PerMessageContextLifetimeManager.CurrentMessageContext = null; MessageCount++; } } }); }
static void ServiceTest() { ReduceProduct reduceProduct = new ReduceProduct { ProductId = new Guid("2B6FDE83-A319-433B-9FA5-399D382D0CD3"), ReduceCount = 1 }; var _commandBus = IoCFactory.Resolve <ICommandBus>(); _commandBus.Start(); var t = _commandBus.SendAsync(reduceProduct, true).Result; Console.WriteLine(t.Reply.Result); var products = _commandBus.SendAsync(new GetProducts { ProductIds = new List <Guid> { reduceProduct.ProductId } }, true).Result.ReadAsAsync <List <Project> >().Result; Console.WriteLine(products.ToJson()); Console.ReadLine(); }
TService IUnitOfWork.GetDomainService <TService>(string name) { //var service = typeof(TService).IsClass ? Activator.CreateInstance<TService>() : IoCFactory.Resolve<TService>(name); var service = IoCFactory.Resolve <TService>(name); this.Joint(service); return(service); }
private static object GetInstance(Type type) { // Change this line if you're not using the CSL, // but a DI framework directly. //return Microsoft.Practices.ServiceLocation // .ServiceLocator.Current.GetInstance(type); return(IoCFactory.Resolve(type)); }
public MessageStore(string connectionString = null) : base(connectionString ?? "MessageStore") { if (IoCFactory.IsInit()) { _logger = IoCFactory.Resolve <ILoggerFactory>().Create(GetType()); } }
public EventPublisher(string id, string topic, EQueueClientsProducers.ProducerSetting producerSetting) { Topic = topic; Id = id; _Logger = IoCFactory.Resolve <ILoggerFactory>().Create(this.GetType()); MessageQueue = new BlockingCollection <EQueueProtocols.Message>(); Producer = new EQueueClientsProducers.Producer(Id, producerSetting); }
protected override IEnumerable <IMessageContext> GetAllUnSentMessages() { using (var messageStore = IoCFactory.Resolve <IMessageStore>("perResolveMessageStore")) { return(messageStore.GetAllUnSentCommands((messageId, message, topic, correlationId) => _messageQueueClient.WrapMessage(message, topic: topic, messageId: messageId, correlationId: correlationId))); } }
public void Initialize() { Configuration.Instance .UseUnityContainer() .RegisterCommonComponents(); _cacheManager = IoCFactory.Resolve <ICacheManager>(); }
public EventSubscriber(string subscriptionName, IHandlerProvider handlerProvider, string[] subEndPoints) : base(handlerProvider, subscriptionName) { SubEndPoints = subEndPoints; _ReceiveWorkTasks = new List <Task>(); MessageQueue = new BlockingCollection <IMessageContext>(); _Logger = IoCFactory.Resolve <ILoggerFactory>().Create(this.GetType()); }
public MessageSender(IMessageQueueClient messageQueueClient, string defaultTopic = null) { _messageQueueClient = messageQueueClient; _defaultTopic = defaultTopic; _needMessageStore = Configuration.Instance.NeedMessageStore; _messageStateQueue = new BlockingCollection <MessageState>(); _logger = IoCFactory.IsInit() ? IoCFactory.Resolve <ILoggerFactory>().Create(GetType().Name) : null; }
public SlidingDoor(Action <int, long> commitOffset, int partition, bool commitPerMessage = false) { _commitOffset = commitOffset; _partition = partition; _offsets = new SortedSet <long>(); _commitPerMessage = commitPerMessage; _logger = IoCFactory.Resolve <ILoggerFactory>().Create(this.GetType().Name); }
public void TestMethod2() { SimplifyDDDConfiguration.Instance.RegisterEntLibLogging(); var logFactory = IoCFactory.Resolve <ILoggerFactory>(); var logger = logFactory.Create(); logger.Debug("test"); }
public CommandConsumer(IHandlerProvider handlerProvider, string receiveEndPoint) : base(handlerProvider) { MessageQueue = new BlockingCollection <IMessageContext>(); ReceiveEndPoint = receiveEndPoint; ReplySenders = new Dictionary <string, ZmqSocket>(); _Logger = IoCFactory.Resolve <ILoggerFactory>().Create(this.GetType()); }
public MessageProcessor(IProcessingMessageScheduler <IMessageContext> scheduler, int batchCount = 100) { _logger = IoCFactory.IsInit() ? IoCFactory.Resolve <ILoggerFactory>().Create(GetType()) : null; _batchCount = batchCount; _processingMessageScheduler = scheduler; MailboxDictionary = new ConcurrentDictionary <string, ProcessingMailbox <IMessageContext> >(); _mailboxProcessorCommands = new BlockingCollection <IMailboxProcessorCommand>(); _cancellationSource = new CancellationTokenSource(); }
/// <summary> /// 获取数据库上下文 /// </summary> /// <param name="dbContextType">数据库上下文类型</param> /// <returns>数据库上下文</returns> public DbContext GetDbContext(Type dbContextType) { if (!dbContexts.ContainsKey(dbContextType)) { dbContexts[dbContextType] = (DbContext)IoCFactory.Resolve(dbContextType); } CheckLazyLoad(); return(dbContexts[dbContextType]); }
protected void ConsumeMessage(BrokeredMessage brokeredMessage) { var eventContext = new MessageContext(brokeredMessage); var message = eventContext.Message; var messageHandlerTypes = _handlerProvider.GetHandlerTypes(message.GetType()); if (messageHandlerTypes.Count == 0) { return; } messageHandlerTypes.ForEach(messageHandlerType => { PerMessageContextLifetimeManager.CurrentMessageContext = eventContext; eventContext.ToBeSentMessageContexts.Clear(); var messageStore = IoCFactory.Resolve <IMessageStore>(); var subscriptionName = string.Format("{0}.{1}", _subscriptionName, messageHandlerType.FullName); if (!messageStore.HasEventHandled(eventContext.MessageID, subscriptionName)) { try { var messageHandler = IoCFactory.Resolve(messageHandlerType); ((dynamic)messageHandler).Handle((dynamic)message); var commandContexts = eventContext.ToBeSentMessageContexts; var eventBus = IoCFactory.Resolve <IEventBus>(); var messageContexts = new List <MessageContext>(); eventBus.GetMessages().ForEach(msg => messageContexts.Add(new MessageContext(msg))); messageStore.SaveEvent(eventContext, subscriptionName, commandContexts, messageContexts); if (commandContexts.Count > 0) { ((CommandBus)IoCFactory.Resolve <ICommandBus>()).SendCommands(commandContexts.AsEnumerable()); } if (messageContexts.Count > 0) { IoCFactory.Resolve <IEventPublisher>().Publish(messageContexts.ToArray()); } } catch (Exception e) { if (e is DomainException) { _logger.Warn(message.ToJson(), e); } else { //IO error or sytem Crash _logger.Error(message.ToJson(), e); } messageStore.SaveFailHandledEvent(eventContext, subscriptionName, e); } finally { PerMessageContextLifetimeManager.CurrentMessageContext = null; } } }); }
public ServiceBusClient(string serviceBusConnectionString) { _serviceBusConnectionString = serviceBusConnectionString; _namespaceManager = NamespaceManager.CreateFromConnectionString(_serviceBusConnectionString); _messageFactory = MessagingFactory.CreateFromConnectionString(_serviceBusConnectionString); _topicClients = new ConcurrentDictionary <string, TopicClient>(); _queueClients = new ConcurrentDictionary <string, QueueClient>(); _logger = IoCFactory.Resolve <ILoggerFactory>().Create(GetType()); }