public BasketViewModel( ILookAfterPets petRepository, ILookAfterAccessories accessoryRepository, IHandleMessages messenger, IEventAggregator events) { _petRepository = petRepository; _accessoryRepository = accessoryRepository; _messenger = messenger; _petBasket = new List<Pet>(); _accessoryBasket = new List<Accessory>(); events.GetEvent<NewPetEvent>().Subscribe(pet => NotifyPropertyChanged("AllAvailablePets")); events.GetEvent<SoldPetEvent>().Subscribe(pet => NotifyPropertyChanged("AllAvailablePets")); _accessoryRepository.OnAccessorySelected((o, e) => { foreach (var accessory in e.Accessories) { if (!_accessoryBasket.Contains(accessory)) { _accessoryBasket.Add(accessory); } } NotifyPropertyChanged("Basket", "HasItemsInBasket", "Total", "PurchaseAllowed"); }); _accessoryRepository.OnAccessoryUnselected((o, e) => { _accessoryBasket.RemoveAll( a => e.Accessories.Contains(a)); NotifyPropertyChanged("Basket", "HasItemsInBasket", "Total", "PurchaseAllowed"); }); }
/// <summary> /// Try to get idempotent's saga data, or return null if handler is not an idempotent saga handler. /// </summary> /// <param name="handler">The handler.</param> /// <returns></returns> private static IIdempotentSagaData TryGetSagaData(IHandleMessages handler) { if (!(handler is Saga)) return null; var sagaData = handler.GetType().GetProperty("Data"); return sagaData.GetValue(handler, null) as IIdempotentSagaData; }
ISagaData CreateSagaData <TMessage>(IHandleMessages <TMessage> handler) { var dataProperty = handler.GetType().GetProperty("Data"); var sagaData = (ISagaData)Activator.CreateInstance(dataProperty.PropertyType); sagaData.Id = Guid.NewGuid(); return(sagaData); }
protected BasePackageTest() { RefreshDb(false); Container.Install(new WindsorInstaller()); WriteRepo = Container.Resolve<INEventStoreRepository<Package>>(); Handler = Container.Resolve<IHandleMessages>(); }
public CommandHandlerTestFixture() { var fixture = new Fixture(); Command = fixture.Create <TCommand>(); Mediator = new Mock <IMediator>(); Handler = ConstructHandler(); }
protected BaseDataProviderTest() { RefreshDb(); Container.Install(new WindsorInstaller()); WriteRepo = Container.Resolve<INEventStoreRepository<DataProvider>>(); Handler = Container.Resolve<IHandleMessages>(); }
public DailyExtractLotHandler(IBusHandler bus, IHandleMessages <DomainNotification> notifications, IUoW uow, IDailyExtractLotCreateDomainService dailyExtractLotCreateDomainService, IDailyExtractLotRepository dailyExtractLotRepository) : base(bus, notifications, uow) { _dailyExtractLotCreateDomainService = dailyExtractLotCreateDomainService; _dailyExtractLotRepository = dailyExtractLotRepository; }
public async Task Run(IHandleMessages <TMessage> handler) { Guard.AgainstNull(handler, nameof(handler)); hasRun = true; await TestContextValidator.Validate(message, Headers, Extensions, Builder); await handler.Handle(message, this); AddDataIfSaga(handler); }
public static async Task <ValidatingContext <TMessage> > Run <TMessage>(IHandleMessages <TMessage> handler, TMessage message) where TMessage : class { Guard.AgainstNull(message, nameof(message)); Guard.AgainstNull(handler, nameof(handler)); var context = Build(message); await context.Run(handler); return(context); }
/// <summary> /// Try to get idempotent's saga data, or return null if handler is not an idempotent saga handler. /// </summary> /// <param name="handler">The handler.</param> /// <returns></returns> private static IIdempotentSagaData TryGetSagaData(IHandleMessages handler) { if (!(handler is Saga)) { return(null); } var sagaData = handler.GetType().GetProperty("Data"); return(sagaData.GetValue(handler, null) as IIdempotentSagaData); }
public RunHealthCheckCommandHandlerTestsFixture() { DistributedCache = new Mock <IDistributedCache>(); Logger = new Mock <ILogger <RunHealthCheckCommandHandler> >(); MessageId = Guid.NewGuid().ToString(); Command = new RunHealthCheckCommand(); MessageHandlerContext = new TestableMessageHandlerContext { MessageId = MessageId }; CommandHandler = new RunHealthCheckCommandHandler(DistributedCache.Object, Logger.Object); }
/// <summary> /// Registers the specified handler. /// </summary> /// <typeparam name="T">Type of message.</typeparam> /// <param name="handler">The handler.</param> public void Register <T> (IHandleMessages <T> handler) where T : class, ICommitEvent { if (_eventUpdaters.ContainsKey(typeof(T))) { _eventUpdaters[typeof(T)].Add((@event => handler.Handle(@event as T))); } else { _eventUpdaters.Add(typeof(T), new List <Action <object> > { (@event => handler.Handle(@event as T)) }); } }
// ReSharper restore UnusedMember.Local static async Task DoDispatch <TMessage>(TMessage message, IHandleMessages handler) { var ordinaryHandler = handler as IHandleMessages <TMessage>; if (ordinaryHandler != null) { ordinaryHandler.Handle(message); } var asyncHandler = handler as IHandleMessagesAsync <TMessage>; if (asyncHandler != null) { await asyncHandler.Handle(message); } }
private IHandlerActivator Setup(IHandleMessages testHandler, Type messageHandlerType) { var services = new ServiceCollection(); services .AddSingleton(messageHandlerType, testHandler) .AddRebus(config => config .Logging(l => l.None()) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "Messages")) .Routing(r => r.TypeBased().MapAssemblyOf <Parent>("Messages"))); var provider = Using(services.BuildServiceProvider()) .UseRebus(); return(provider.GetRequiredService <IHandlerActivator>()); }
public StorageQueueListener(IQueueConfiguration queueConfiguration, IQueueListeningConfiguration queueListeningConfiguration, IHandleMessages messageHandler, IEnumerable <ILogReplicationStatus> replicationStatusLoggers) { _messageHandler = messageHandler; _replicationStatusLoggers = replicationStatusLoggers; _maximumReceiveBatchSize = queueListeningConfiguration.QueueMessageReceiveBatchSize ?? QueueListeningConfigurationDefaults.QueueMessageReceiveBatchSize; _invisibilityTimeoutInSeconds = queueListeningConfiguration.QueueMessageInvisibilityTimeoutInSeconds ?? QueueListeningConfigurationDefaults.QueueMessageInvisibilityTimeoutInSeconds; _maximumBackOffDurationInSeconds = queueListeningConfiguration.MaximumQueueRetrievalBackOffDurationInSeconds ?? QueueListeningConfigurationDefaults.MaximumQueueRetrievalBackOffDurationInSeconds; _maximumHandleConcurrency = queueListeningConfiguration.MaximumNumberOfConcurrentMessageHandlers ?? QueueListeningConfigurationDefaults.MaximumNumberOfConcurrentMessageHandlers; _maximumNumberOfRetries = queueListeningConfiguration.MaximumNumberOfRetriesOnFailure ?? QueueListeningConfigurationDefaults.MaximumNumberOfRetriesOnFailure; _concurrencyLimiter = new SemaphoreSlim(_maximumHandleConcurrency, _maximumHandleConcurrency); _queueClient = new QueueClient(queueConfiguration.QueueConnectionString, queueConfiguration.QueueName ?? ReplicationConfigurationDefaults.ReplicationQueueName); _queueClient.CreateIfNotExists(); }
/// <summary> /// Private dispatcher method that gets invoked only via reflection. /// </summary> // ReSharper disable UnusedMember.Local async Task DispatchToHandler <TMessage>(TMessage message, IHandleMessages handler) { var saga = handler as Saga; if (saga != null) { saga.ConfigureHowToFindSaga(); var sagaData = GetSagaData(message, saga); if (sagaData == null) { if (handler is IAmInitiatedBy <TMessage> || handler is IAmInitiatedByAsync <TMessage> ) { saga.IsNew = true; saga.Complete = false; sagaData = CreateSagaData(handler); } else { log.Warn("No saga data was found for {0}/{1}", message, handler); UncorrelatedMessage(message, saga); return; } } else { saga.IsNew = false; saga.Complete = false; } handler.GetType().GetProperty(sagaDataPropertyName).SetValue(handler, sagaData, null); using (new SagaContext(sagaData.Id)) { await DoDispatch(message, handler); PerformSaveActions(saga, sagaData); } return; } await DoDispatch(message, handler); }
/// <summary> /// Default services with a singleton for Timebomb changed /// hanlder running against the default queue /// </summary> /// <param name="handler"></param> /// <returns></returns> public static IServiceCollection DefaultServices( IHandleMessages <TimebombChangedEvent> handler, int numberOfWorkers = 1 ) { var services = new ServiceCollection(); services.AddSingleton <Options>(new Options { NumberOfWorkers = numberOfWorkers }); services.AddSingleton <SimpleRetryStrategySettings>(SimpleRetryStrategySettings); services.AddSingleton <IHandleMessages <TimebombChangedEvent> >(handler); services.AddTransient <ISomeDependency, SomeDependency>(); services.AddTransient <IHandleMessages <ChangedEvent>, ChangedHandler>(); services .WithDefaultPipeline(DefaultQueue) .UseInMemoryBus(); return(services); }
public static IServiceCollection MultiHanlderServices( IHandleMessages <TimebombChangedEvent> handler1, IHandleMessages <ChangedEvent> handler2, int numberOfWorkers = 1 ) { var services = new ServiceCollection(); services.AddSingleton <Options>(new Options { NumberOfWorkers = numberOfWorkers }); services.AddSingleton <SimpleRetryStrategySettings>(SimpleRetryStrategySettings); services.AddSingleton <IHandleMessages <TimebombChangedEvent> >(handler1); services.AddSingleton <IHandleMessages <ChangedEvent> >(handler2); services .WithDefaultPipeline(DefaultQueue) .UseInMemoryBus(); return(services); }
/// <summary> /// Tears down idemptency handling infraestructure for the current message & handler. /// </summary> /// <param name="bus">The bus.</param> /// <param name="message">The message.</param> /// <param name="handler">The handler.</param> private void OnAfterHandlingEvent(IBus bus, object message, IHandleMessages handler) { var idempotentSagaData = TryGetSagaData(handler); if (idempotentSagaData == null) { // Not idempotent? ok, do nothing.. return; } var mcontext = MessageContext.GetCurrent(); var icontext = mcontext.Items[Headers.IdempotentSagaResults] as IdempotentSagaResults; if (icontext != null) { log.Debug("Saving results for idempotent invocation of message: {0} (Handler: {1})", mcontext.RebusTransportMessageId, handler.GetType()); // Store results of current message handling into our idempotency store. idempotentSagaData.ExecutionResults.Add(icontext); } RemoveIdempotencyContext(); }
public HandlerActivatorForTesting UseHandler(IHandleMessages handler) { return(UseHandler(handler.GetType(), () => handler)); }
public static Task OnMessage <T>(this IHandleMessages <T> handler, TestableMessageHandlerContext context, Action <T> messageCreator) where T : IMessage { var message = Test.CreateInstance(messageCreator); return(handler.Handle(message, context)); }
public FplNextGwHandlerTests(ITestOutputHelper logger) { _client = Factory.GetHandler <FplNextGameweekCommandHandler>(logger); }
public MessageHandler(IHandleMessages <TMessage> handler) { this.handler = handler; }
public virtual MessageHandlerWireup AddHandler <TMessage>(IHandleMessages <TMessage> handler) { return(this.AddHandler(c => handler)); }
public static void Handle <T>(this IHandleMessages <T> handler, Action <T> a2) where T : IMessage { handler.Handle(MessageCreator.CreateMessage(a2)); }
public FplTransfersCommandHandlerTests(ITestOutputHelper logger) { _client = Factory.GetHandler <FplTransfersCommandHandler>(logger); }
internal void RaiseBeforeHandling(IBus bus, object message, IHandleMessages handler) { BeforeHandling(bus, message, handler); }
internal void RaiseAfterHandling(IBus bus, object message, IHandleMessages handler) { AfterHandling(bus, message, handler); }
void RaiseAfterHandling(object message, IHandleMessages handler) { AfterHandling(message, handler); }
public DataProviderController(IHandleMessages handler) { _handler = handler; }
public FplCaptainCommandHandlerTests(ITestOutputHelper logger) { _client = Factory.GetHandler <FplCaptainCommandHandler>(logger); }
/// <summary> /// Creates instance of HandlerInvoker /// </summary> protected virtual HandlerInvoker CreateHandlerInvoker <TMessage>(IHandleMessages <TMessage> handler, TMessage message, ITransactionContext transactionContext, Message logicalMessage) { return(new HandlerInvoker <TMessage>(() => handler.Handle(message), handler, transactionContext)); }
public BusinessRulesValidator(IHandleMessages handler) { _handler = handler; }
public static void RegisterHandler <TMessage>(IHandleMessages <TMessage> handler) { RegisterHandler(c => handler); }
/// <summary> /// Extension method on <see cref="IHandleMessages{T}"/>. Users can avoid declaring an <see cref="IBus"/> to be injected, and use the bus implicitly. /// </summary> /// <example> The following is an example on how a <see cref="IHandleMessages{T}"/> might look like using the <see cref="Bus{T}"/> extension method: /// <code escaped="false"> /// public class RequestDataMessageHandler : IHandleMessages<RequestDataMessage> /// { /// public void Handle(RequestDataMessage message) /// { /// var response = this.Bus().CreateInstance<DataResponseMessage>(m => /// { /// m.DataId = message.DataId; /// m.String = message.String; /// }); /// this.Bus().Reply(response); /// } /// } /// </code> /// </example> /// <typeparam name="T">The message type to handle.</typeparam> /// <param name="handler">The <see cref="IHandleMessages{T}" /> implementing class.</param> /// <returns><see cref="IBus"/> interface.</returns> public static IBus Bus <T>(this IHandleMessages <T> handler) { return(ExtensionMethods.Bus); }
/// <summary> /// Returns all relevant handler instances for the given message by looking up compatible registered functions and instance factory methods. /// </summary> public async Task <IEnumerable <IHandleMessages <TMessage> > > GetHandlers <TMessage>(TMessage message, ITransactionContext transactionContext) { if (message == null) { throw new ArgumentNullException(nameof(message)); } if (transactionContext == null) { throw new ArgumentNullException(nameof(transactionContext)); } var messageContext = MessageContext.Current; if (messageContext == null) { throw new InvalidOperationException("Attempted to resolve handler with message context, but no current context could be found on MessageContext.Current"); } var handlerFactories = _cachedHandlerFactories.GetOrAdd(typeof(TMessage), type => { var noArgumentsInvokers = _handlerFactoriesNoArguments .OfType <Func <IHandleMessages <TMessage> > >() .Select(factory => (Func <IMessageContext, IHandleMessages>)(context => factory())); var contextArgumentInvokers = _handlerFactoriesMessageContextArgument .OfType <Func <IMessageContext, IHandleMessages <TMessage> > >() .Select(factory => (Func <IMessageContext, IHandleMessages>)(factory)); var busAndContextInvokers = _handlerFactoriesBusAndMessageContextArguments .OfType <Func <IBus, IMessageContext, IHandleMessages <TMessage> > >() .Select(factory => (Func <IMessageContext, IHandleMessages>)(context => factory(Bus, context))); return(noArgumentsInvokers.Concat(contextArgumentInvokers).Concat(busAndContextInvokers).ToArray()); }); // ReSharper disable once CoVariantArrayConversion var instances = (IHandleMessages <TMessage>[])_cachedHandlers.GetOrAdd(typeof(TMessage), type => _handlerInstances .OfType <IHandleMessages <TMessage> >().ToArray()); var result = new IHandleMessages <TMessage> [handlerFactories.Length + instances.Length]; for (var index = 0; index < handlerFactories.Length; index++) { result[index] = (IHandleMessages <TMessage>)handlerFactories[index](messageContext); } transactionContext.OnDisposed(context => { for (var index = 0; index < handlerFactories.Length; index++) { if (result[index] is IDisposable disposable) { disposable.Dispose(); } } }); Array.Copy(instances, 0, result, handlerFactories.Length, instances.Length); return(result); }
void RaiseBeforeHandling(object message, IHandleMessages handler) { BeforeHandling(message, handler); }
public RebusLogDecorator(IHandleMessages <T> inner) { _inner = inner; }
/// <summary> /// Sets up idemptency infraestructure before handling of message begins. /// </summary> /// <param name="bus">The bus.</param> /// <param name="message">The message.</param> /// <param name="handler">The handler.</param> private void OnBeforeHandlingEvent(IBus bus, object message, IHandleMessages handler) { var mcontext = MessageContext.GetCurrent(); var idempotentSagaData = TryGetSagaData(handler); if (idempotentSagaData == null) { // Not idempotent? ok, do nothing.. return; } // Create a list to store execution results and side effects. if (idempotentSagaData.ExecutionResults == null) { idempotentSagaData.ExecutionResults = new List<IdempotentSagaResults>(); } // Let's see if we have a recorded results from a previous invocation. var handlingResults = idempotentSagaData.ExecutionResults.SingleOrDefault(x => x.Id == mcontext.RebusTransportMessageId); if (handlingResults == null) { // There's no record of previous handling of this message for this handler, so let's initialize our // idempotent saga-data storage, so our hooks can save any generated side-effects. EstablishIdempotencyContextFor(idempotentSagaData, mcontext); } else { // This is a message already handled, so we should avoid calling handlers, just re-apply any side effect and move on. ResendStoredSideEffects(bus, handlingResults, mcontext); // Avoid bus worker from handling (again) this message with current handler. mcontext.SkipHandler(handler.GetType()); } }
public static Task OnMessage <T>(this IHandleMessages <T> handler, TestableMessageHandlerContext context, T message) where T : IMessage { return(handler.Handle(message, context)); }
/// <summary> /// Tears down idemptency handling infraestructure for the current message & handler. /// </summary> /// <param name="bus">The bus.</param> /// <param name="message">The message.</param> /// <param name="handler">The handler.</param> private void OnAfterHandlingEvent(IBus bus, object message, IHandleMessages handler) { var idempotentSagaData = TryGetSagaData(handler); if (idempotentSagaData == null) { // Not idempotent? ok, do nothing.. return; } var mcontext = MessageContext.GetCurrent(); var icontext = mcontext.Items[Headers.IdempotentSagaResults] as IdempotentSagaResults; if (icontext != null) { log.Debug("Saving results for idempotent invocation of message: {0} (Handler: {1})", mcontext.RebusTransportMessageId, handler.GetType()); // Store results of current message handling into our idempotency store. idempotentSagaData.ExecutionResults.Add(icontext); } RemoveIdempotencyContext(); }
public when_amending_data_provider_structure() { RefreshDb(); Container.Install(new WindsorInstaller()); _handler = Container.Resolve<IHandleMessages>(); _writeRepo = Container.Resolve<INEventStoreRepository<DataProvider>>(); _amendHandler = new AmendDataProviderStructureHandler(_writeRepo, new DataProviderResponseRepository()); Mapper.CreateMap<AmendedIvidDataProvider, IEnumerable<IDataField>>() .ConvertUsing(Mapper.Map<object, IEnumerable<DataField>>); Mapper.CreateMap<VehicleData, DataField>() .ForMember(d => d.Name, opt => opt.MapFrom(x => "VehicleData")) .ForMember(d => d.Type, opt => opt.MapFrom(x => x.GetType())) .ForMember(d => d.DataFields, opt => opt.MapFrom(x => Mapper.Map<object, IEnumerable<DataField>>(x))); }
private static ValueTask Handle(IHandleMessages handler, Message m) { return(new ValueTask()); }