Пример #1
0
        public static void AddProducer(this MessagingOptions builder, Action <ProducerConfig> configuration)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var config = new ProducerConfig();

            configuration(config);

            if (config.ProducerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(config.ProducerConfiguration));
            }

            builder.Container.Register(typeof(IEnumerable <MessageConfiguration>), () => config.MessageConfigurations.Select(a =>
            {
                var c = new MessageConfiguration();
                c.Init(a);
                return(c);
            }), Lifestyle.Singleton);

            builder.Container.Register(typeof(IMessageConfigurationProvider <>), typeof(MessageConfigurationProvider <>), Lifestyle.Singleton);
            builder.Container.RegisterSingleton <IProducerFactory, ProducerFactory>();
            builder.Container.RegisterSingleton <IProducerConfiguration>(config);

            builder.HasProducer = true;
        }
Пример #2
0
 public InMemoryMessageBroker(IModuleClient moduleClient, IAsyncMessageDispatcher asyncMessageDispatcher,
                              MessagingOptions messagingOptions)
 {
     _moduleClient           = moduleClient;
     _asyncMessageDispatcher = asyncMessageDispatcher;
     _messagingOptions       = messagingOptions;
 }
Пример #3
0
        public static MessagingOptions UseRabbitMQBroker(
            this MessagingOptions options,
            Action <IMessageBroker> brokerAction = null,
            string section = "naos:messaging:rabbitMQ",
            IEnumerable <Assembly> assemblies = null)
        {
            EnsureArg.IsNotNull(options, nameof(options));
            EnsureArg.IsNotNull(options.Context, nameof(options.Context));

            options.Context.Services.AddSingleton <IMessageBroker>(sp =>
            {
                var rabbitMQConfiguration = options.Context.Configuration.GetSection(section).Get <RabbitMQConfiguration>();
                var broker = new RabbitMQMessageBroker(o => o
                                                       .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                       .Host(rabbitMQConfiguration.Host)
                                                       .HandlerFactory(new ServiceProviderMessageHandlerFactory(sp)));

                brokerAction?.Invoke(broker);
                return(broker);
            });

            options.Context.Messages.Add($"{LogKeys.Startup} naos services builder: messaging added (broker={nameof(RabbitMQMessageBroker)})");

            return(options);
        }
Пример #4
0
        }                                    // might hold metadata used by response pipeline

        public CallbackData(
            Action <Message, TaskCompletionSource <object> > callback,
            Func <Message, bool> resendFunc,
            TaskCompletionSource <object> ctx,
            Message msg,
            Action <Message> unregisterDelegate,
            MessagingOptions messagingOptions,
            ILogger logger,
            ILogger timerLogger)
        {
            // We are never called without a callback func, but best to double check.
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }
            // We are never called without a resend func, but best to double check.
            if (resendFunc == null)
            {
                throw new ArgumentNullException(nameof(resendFunc));
            }
            this.logger           = logger;
            this.callback         = callback;
            this.resendFunc       = resendFunc;
            context               = ctx;
            Message               = msg;
            unregister            = unregisterDelegate;
            alreadyFired          = false;
            this.messagingOptions = messagingOptions;
            this.TransactionInfo  = TransactionContext.GetTransactionInfo();
            this.timerLogger      = timerLogger;
        }
Пример #5
0
        public void Constructor_Initialises_Correctly()
        {
            var target = new MessagingOptions();

            Assert.Null(target.Url);
            Assert.False(target.HasUrl);
        }
Пример #6
0
        public static MessagingOptions UseSignalRBroker(
            this MessagingOptions options,
            Action <IMessageBroker> brokerAction = null,
            string messageScope = null,
            string section      = "naos:messaging:signalr")
        {
            EnsureArg.IsNotNull(options, nameof(options));
            EnsureArg.IsNotNull(options.Context, nameof(options.Context));

            options.Context.Services.AddSingleton <IMessageBroker>(sp =>
            {
                var configuration = options.Context.Configuration.GetSection(section).Get <SignalRConfiguration>();
                var broker        = new SignalRServerlessMessageBroker(o => o
                                                                       .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                       .Mediator((IMediator)sp.CreateScope().ServiceProvider.GetService(typeof(IMediator)))
                                                                       .HandlerFactory(new ServiceProviderMessageHandlerFactory(sp))
                                                                       .ConnectionString(configuration.ConnectionString)
                                                                       .HttpClient(sp.GetRequiredService <IHttpClientFactory>())
                                                                       .Map(sp.GetRequiredService <ISubscriptionMap>())
                                                                       .FilterScope(Environment.GetEnvironmentVariable(EnvironmentKeys.IsLocal).ToBool()
                            ? Environment.MachineName.Humanize().Dehumanize().ToLower()
                            : string.Empty)
                                                                       .MessageScope(messageScope));

                brokerAction?.Invoke(broker);
                return(broker);
            });

            options.Context.Messages.Add($"{LogEventKeys.Startup} naos services builder: messaging added (broker={nameof(SignalRServerlessMessageBroker)})");

            return(options);
        }
 public BaseKafkaProducer(IOptions <MessagingOptions> options,
                          ILogger <BaseKafkaProducer <TMessage> > logger)
 {
     _options  = options?.Value ?? throw new ArgumentNullException(nameof(options));
     _logger   = logger;
     _producer = GetProducer();
 }
Пример #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AccountController" />
 /// class.
 /// </summary>
 /// <param name="userManager">The user manager.</param>
 /// <param name="messageBuilder">The message builder.</param>
 /// <param name="mailer">The mailer.</param>
 /// <param name="options">The options.</param>
 /// <param name="logger">The logger.</param>
 /// <exception cref="ArgumentNullException">null options or userManager or
 /// signInManager or environment or messageBuilder or mailer</exception>
 public AccountController(UserManager <ApplicationUser> userManager,
                          IMessageBuilderService messageBuilder,
                          IMailerService mailer,
                          IOptions <MessagingOptions> options,
                          ILogger <AccountController> logger)
 {
     if (options == null)
     {
         throw new ArgumentNullException(nameof(options));
     }
     _userManager = userManager ??
                    throw new ArgumentNullException(nameof(userManager));
     //_signInManager = signInManager ??
     //    throw new ArgumentNullException(nameof(signInManager));
     //_environment = environment ??
     //    throw new ArgumentNullException(nameof(environment));
     _messageBuilder = messageBuilder ??
                       throw new ArgumentNullException(nameof(messageBuilder));
     _mailer  = mailer ?? throw new ArgumentNullException(nameof(mailer));
     _options = options.Value;
     //_configuration = configuration ??
     //    throw new ArgumentNullException(nameof(configuration));
     _logger = logger ??
               throw new ArgumentNullException(nameof(logger));
 }
        //============================================================================================= Static API

        public static SecuritySystem StartSecurity(ISecurityDataProvider securityDataProvider,
                                                   IMessageProvider messageProvider,
                                                   IMissingEntityHandler missingEntityHandler,
                                                   MessagingOptions messagingOptions)
        {
            var securityConfig = new SecurityConfiguration
            {
                SystemUserId    = Identifiers.SystemUserId,
                VisitorUserId   = Identifiers.VisitorUserId,
                EveryoneGroupId = Identifiers.EveryoneGroupId,
                OwnerGroupId    = Identifiers.OwnersGroupId
            };

            var securitySystem = new SecuritySystem(securityDataProvider, messageProvider, missingEntityHandler,
                                                    securityConfig, messagingOptions);

            securitySystem.Start();

            SnLog.WriteInformation("Security subsystem started in Search service", EventId.RepositoryLifecycle,
                                   properties: new Dictionary <string, object> {
                { "DataProvider", securityDataProvider.GetType().FullName },
                { "MessageProvider", messageProvider.GetType().FullName }
            });

            return(securitySystem);
        }
Пример #10
0
        internal static SecuritySystem StartTheSystem(ISecurityDataProvider securityDataProvider)
        {
            var messageSenderManager = new MessageSenderManager("asdf");
            // Call SecurityContext starter method.
            //var securitySystem = SecurityContextForConcurrencyTests.StartTheSystem(new SecurityConfiguration
            //{
            //    SecurityDataProvider = securityDataProvider,
            //    MessageProvider = new DefaultMessageProvider(messageSenderManager),
            //    CommunicationMonitorRunningPeriodInSeconds = 31
            //});
            var config           = new SecurityConfiguration();
            var messagingOptions = new MessagingOptions {
                CommunicationMonitorRunningPeriodInSeconds = 31
            };
            var securitySystem = new SecuritySystem(securityDataProvider,
                                                    new DefaultMessageProvider(messageSenderManager),
                                                    new MissingEntityHandler(), config, messagingOptions);

            securitySystem.Start();

            // legacy logic
            // original line: MessageSender.Initialize("asdf");
            //securitySystem.MessageSenderManager = messageSenderManager;

            return(securitySystem);
        }
Пример #11
0
 public MessageBroker(IModuleClient moduleClient, IBusPublisher busPublisher,
                      IAsyncMessageDispatcher asyncMessageDispatcher, MessagingOptions messagingOptions)
 {
     _moduleClient           = moduleClient;
     _busPublisher           = busPublisher;
     _asyncMessageDispatcher = asyncMessageDispatcher;
     _messagingOptions       = messagingOptions;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="Invocation"/> class.
 /// </summary>
 /// <param name="requestMessage">The request message.</param>
 /// <param name="messagingOptions">Messaging options.</param>
 /// <param name="partitionId">The identifier of the target partition.</param>
 /// <param name="cancellationToken">A cancellation token.</param>
 /// <remarks>
 /// <para>If the target partition cannot be mapped to an available member, another random member will be used.</para>
 /// </remarks>
 public Invocation(ClientMessage requestMessage, MessagingOptions messagingOptions, int partitionId, CancellationToken cancellationToken)
     : this(requestMessage, messagingOptions, cancellationToken)
 {
     if (partitionId < 0)
     {
         throw new ArgumentException("Must be a positive integer.", nameof(partitionId));
     }
     TargetPartitionId = partitionId;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="Invocation"/> class.
 /// </summary>
 /// <param name="requestMessage">The request message.</param>
 /// <param name="messagingOptions">Messaging options.</param>
 /// <param name="targetMemberId">The identifier of the target member.</param>
 /// <param name="cancellationToken">A cancellation token.</param>
 /// <remarks>
 /// <para>If the target member is not available, another random member will be used.</para>
 /// </remarks>
 public Invocation(ClientMessage requestMessage, MessagingOptions messagingOptions, Guid targetMemberId, CancellationToken cancellationToken)
     : this(requestMessage, messagingOptions, cancellationToken)
 {
     if (targetMemberId == default)
     {
         throw new ArgumentException("Must be a non-default Guid.", nameof(targetMemberId));
     }
     TargetMemberId = targetMemberId;
 }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FileMessageBuilderService"/>
 /// class.
 /// </summary>
 /// <param name="environment">The environment.</param>
 /// <param name="options">The options.</param>
 public FileMessageBuilderService(MessagingOptions options,
                                  IHostEnvironment environment) : base(options)
 {
     // http://stackoverflow.com/questions/35842547/read-solution-data-files-asp-net-core/35863315
     _messageDir = Path.Combine(
         environment.ContentRootPath,
         "wwwroot",
         "messages") + Path.DirectorySeparatorChar;
 }
Пример #15
0
        private int _attemptsCount; // number of times this invocation has been attempted

        /// <summary>
        /// Initializes a new instance of the <see cref="Invocation"/> class.
        /// </summary>
        /// <param name="requestMessage">The request message.</param>
        /// <param name="messagingOptions">Messaging options.</param>
        public Invocation(ClientMessage requestMessage, MessagingOptions messagingOptions)
        {
            RequestMessage    = requestMessage ?? throw new ArgumentNullException(nameof(requestMessage));
            _messagingOptions = messagingOptions ?? throw new ArgumentNullException(nameof(messagingOptions));
            CorrelationId     = requestMessage.CorrelationId;
            InitializeNewCompletionSource();
            _attemptsCount = 1;
            StartTime      = Clock.Milliseconds;
        }
 public InMemoryMessageBroker(IModuleClient moduleClient, IAsyncMessageDispatcher asyncMessageDispatcher,
                              IContext context, IOutbox outbox, MessagingOptions messagingOptions, ILogger <InMemoryMessageBroker> logger)
 {
     _moduleClient           = moduleClient;
     _asyncMessageDispatcher = asyncMessageDispatcher;
     _context          = context;
     _outbox           = outbox;
     _messagingOptions = messagingOptions;
     _logger           = logger;
 }
Пример #17
0
        public EventPublisher(MessagingOptions options)
        {
            var factory = new ConnectionFactory()
            {
                Uri = new Uri(options.ConnectionString)
            };

            _connection = factory.CreateConnection();
            _channel    = _connection.CreateModel();
        }
        public SendMessageService(
            IMapper mapper,
            IOptions <MessagingOptions> messagingOptions)
        {
            _messagingOptions = messagingOptions.Value;
            _mapper           = mapper;

            topicClient = new TopicClient(
                _messagingOptions.ServiceBusConnectionString,
                _messagingOptions.TopicNameToSend);
        }
        private int _attemptsCount; // number of times this invocation has been attempted

        /// <summary>
        /// Initializes a new instance of the <see cref="Invocation"/> class.
        /// </summary>
        /// <param name="requestMessage">The request message.</param>
        /// <param name="messagingOptions">Messaging options.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        public Invocation(ClientMessage requestMessage, MessagingOptions messagingOptions, CancellationToken cancellationToken)
        {
            RequestMessage     = requestMessage ?? throw new ArgumentNullException(nameof(requestMessage));
            _messagingOptions  = messagingOptions ?? throw new ArgumentNullException(nameof(messagingOptions));
            CorrelationId      = requestMessage.CorrelationId;
            _cancellationToken = cancellationToken;
            InitializeNewCompletionSource();
            _registration  = _cancellationToken.Register(TrySetCanceled); // must dispose to de-register!
            _attemptsCount = 1;
            StartTime      = Clock.Milliseconds;
        }
Пример #20
0
 public SharedCallbackData(
     Action <Message> unregister,
     ILogger logger,
     MessagingOptions messagingOptions,
     ApplicationRequestsStatisticsGroup requestStatistics)
 {
     RequestStatistics     = requestStatistics;
     this.Unregister       = unregister;
     this.Logger           = logger;
     this.MessagingOptions = messagingOptions;
     this.ResponseTimeout  = messagingOptions.ResponseTimeout;
 }
Пример #21
0
        public EventSubscriber(MessagingOptions options, IMediator mediator, ILogger <EventSubscriber> logger)
        {
            _mediator = mediator;
            _logger   = logger;

            var factory = new ConnectionFactory {
                Uri = new Uri(options.ConnectionString)
            };

            _connection = factory.CreateConnection();
            _channel    = _connection.CreateModel();
        }
Пример #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MemberConnection"/> class.
        /// </summary>
        /// <param name="address">The network address.</param>
        /// <param name="authenticator">The authenticator.</param>
        /// <param name="messagingOptions">Messaging options.</param>
        /// <param name="networkingOptions">Networking options.</param>
        /// <param name="sslOptions">SSL options.</param>
        /// <param name="correlationIdSequence">A sequence of unique correlation identifiers.</param>
        /// <param name="loggerFactory">A logger factory.</param>
        public MemberConnection(NetworkAddress address, Authenticator authenticator, MessagingOptions messagingOptions, NetworkingOptions networkingOptions, SslOptions sslOptions, ISequence <long> correlationIdSequence, ILoggerFactory loggerFactory)
        {
            Address                = address ?? throw new ArgumentNullException(nameof(address));
            _authenticator         = authenticator ?? throw new ArgumentNullException(nameof(authenticator));
            _messagingOptions      = messagingOptions ?? throw new ArgumentNullException(nameof(messagingOptions));
            _networkingOptions     = networkingOptions ?? throw new ArgumentNullException(nameof(networkingOptions));
            _sslOptions            = sslOptions ?? throw new ArgumentNullException(nameof(sslOptions));
            _correlationIdSequence = correlationIdSequence ?? throw new ArgumentNullException(nameof(correlationIdSequence));
            _loggerFactory         = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
            _logger                = loggerFactory.CreateLogger <MemberConnection>();

            HConsole.Configure(x => x.Configure <MemberConnection>().SetIndent(4).SetPrefix("MBR.CONN"));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MemberConnection"/> class.
        /// </summary>
        /// <param name="address">The network address.</param>
        /// <param name="messagingOptions">Messaging options.</param>
        /// <param name="socketOptions">Socket options.</param>
        /// <param name="sslOptions">SSL options.</param>
        /// <param name="connectionIdSequence">A sequence of unique connection identifiers.</param>
        /// <param name="correlationIdSequence">A sequence of unique correlation identifiers.</param>
        /// <param name="loggerFactory">A logger factory.</param>
        /// <remarks>
        /// <para>The <paramref name="connectionIdSequence"/> parameter can be used to supply a
        /// sequence of unique connection identifiers. This can be convenient for tests, where
        /// using unique identifiers across all clients can simplify debugging.</para>
        /// </remarks>
        public MemberConnection(NetworkAddress address, MessagingOptions messagingOptions, SocketOptions socketOptions, SslOptions sslOptions, ISequence <int> connectionIdSequence, ISequence <long> correlationIdSequence, ILoggerFactory loggerFactory)
        {
            Address                = address ?? throw new ArgumentNullException(nameof(address));
            _messagingOptions      = messagingOptions ?? throw new ArgumentNullException(nameof(messagingOptions));
            _socketOptions         = socketOptions ?? throw new ArgumentNullException(nameof(socketOptions));
            _sslOptions            = sslOptions ?? throw new ArgumentNullException(nameof(sslOptions));
            _connectionIdSequence  = connectionIdSequence ?? throw new ArgumentNullException(nameof(connectionIdSequence));
            _correlationIdSequence = correlationIdSequence ?? throw new ArgumentNullException(nameof(correlationIdSequence));
            _loggerFactory         = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
            _logger                = loggerFactory.CreateLogger <MemberConnection>();

            HConsole.Configure(this, config => config.SetIndent(4).SetPrefix("CLIENT"));
        }
Пример #24
0
 //UNDONE: get configuration through IOptions and register SecuritySystem as a service.
 public SecuritySystem(ISecurityDataProvider dataProvider, IMessageProvider messageProvider,
                       IMissingEntityHandler missingEntityHandler, SecurityConfiguration configuration, MessagingOptions messagingOptions)
 {
     Configuration    = configuration;
     MessagingOptions = messagingOptions;
     dataProvider.ActivitySerializer = new ActivitySerializer(this);
     DataHandler          = new DataHandler(dataProvider, Options.Create(messagingOptions));
     ActivityHistory      = new SecurityActivityHistoryController();
     DataProvider         = dataProvider;
     MessageProvider      = messageProvider;
     MessageSenderManager = messageProvider.MessageSenderManager;
     MissingEntityHandler = missingEntityHandler;
     SystemUser           = new SecuritySystemUser(configuration.SystemUserId);
 }
Пример #25
0
        public static MessagingOptions UseServiceBusBroker(
            this MessagingOptions options,
            Action <IMessageBroker> brokerAction = null,
            string topicName        = null,
            string subscriptionName = null,
            string section          = "naos:messaging:serviceBus")
        {
            EnsureArg.IsNotNull(options, nameof(options));
            EnsureArg.IsNotNull(options.Context, nameof(options.Context));

            var configuration = options.Context.Configuration.GetSection(section).Get <ServiceBusConfiguration>();

            configuration.EntityPath = topicName ?? $"{Environment.GetEnvironmentVariable(EnvironmentKeys.Environment) ?? "Production"}-Naos.Messaging";
            options.Context.Services.AddSingleton <IServiceBusProvider>(sp =>
            {
                if (configuration?.Enabled == true)
                {
                    return(new ServiceBusProvider(
                               sp.GetRequiredService <ILogger <ServiceBusProvider> >(),
                               SdkContext.AzureCredentialsFactory.FromServicePrincipal(configuration.ClientId, configuration.ClientSecret, configuration.TenantId, AzureEnvironment.AzureGlobalCloud),
                               configuration));
                }

                throw new NotImplementedException("no messaging servicebus is enabled");
            });

            options.Context.Services.AddSingleton <IMessageBroker>(sp =>
            {
                var broker = new ServiceBusMessageBroker(o => o
                                                         .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                         .Mediator((IMediator)sp.CreateScope().ServiceProvider.GetService(typeof(IMediator)))
                                                         .Provider(sp.GetRequiredService <IServiceBusProvider>())
                                                         .HandlerFactory(new ServiceProviderMessageHandlerFactory(sp))
                                                         .Map(sp.GetRequiredService <ISubscriptionMap>())
                                                         .SubscriptionName(subscriptionName ?? options.Context.Descriptor.Name) //AppDomain.CurrentDomain.FriendlyName, // PRODUCT.CAPABILITY
                                                         .FilterScope(Environment.GetEnvironmentVariable(EnvironmentKeys.IsLocal).ToBool()
                            ? Environment.MachineName.Humanize().Dehumanize().ToLower()
                            : string.Empty));

                brokerAction?.Invoke(broker);
                return(broker);
            }); // scope the messagebus messages to the local machine, so local events are handled locally

            options.Context.Services.AddHealthChecks()
            .AddAzureServiceBusTopic(configuration.ConnectionString, configuration.EntityPath, "messaging-broker-servicebus");

            options.Context.Messages.Add($"{LogEventKeys.Startup} naos services builder: messaging added (broker={nameof(ServiceBusMessageBroker)})");

            return(options);
        }
 public MongoOutbox(IMongoDatabase database, IModuleRegistry moduleRegistry, OutboxOptions outboxOptions,
                    MessagingOptions messagingOptions, IModuleClient moduleClient, IAsyncMessageDispatcher asyncMessageDispatcher,
                    ILogger <MongoOutbox> logger)
 {
     _database               = database;
     _moduleClient           = moduleClient;
     _asyncMessageDispatcher = asyncMessageDispatcher;
     _logger  = logger;
     Enabled  = outboxOptions.Enabled;
     _modules = moduleRegistry.Modules.ToArray();
     _useBackgroundDispatcher = messagingOptions.UseBackgroundDispatcher;
     _collectionName          = string.IsNullOrWhiteSpace(outboxOptions.CollectionName)
         ? "outbox"
         : outboxOptions.CollectionName;
 }
Пример #27
0
        public void Options()
        {
            var options = new MessagingOptions
            {
                MinRetryDelayMilliseconds = 456,
                MaxFastInvocationCount    = 789
            };

            Assert.That(options.MinRetryDelayMilliseconds, Is.EqualTo(456));
            Assert.That(options.MaxFastInvocationCount, Is.EqualTo(789));

            var clone = options.Clone();

            Assert.That(clone.MinRetryDelayMilliseconds, Is.EqualTo(456));
            Assert.That(clone.MaxFastInvocationCount, Is.EqualTo(789));
        }
Пример #28
0
 public SharedCallbackData(
     Func <Message, bool> resendFunc,
     Action <Message> unregister,
     ILogger logger,
     MessagingOptions messagingOptions,
     SerializationManager serializationManager,
     ApplicationRequestsStatisticsGroup requestStatistics)
 {
     RequestStatistics         = requestStatistics;
     this.ShouldResend         = resendFunc;
     this.Unregister           = unregister;
     this.serializationManager = serializationManager;
     this.Logger           = logger;
     this.MessagingOptions = messagingOptions;
     this.ResponseTimeout  = messagingOptions.ResponseTimeout;
 }
Пример #29
0
        public MessagesService(IOptions <MessagingOptions> messagingOptions,
                               SendMessageService sendMessageService,
                               IMapper mapper,
                               ILogger <MessagesService> logger)
        {
            _messagingOptions   = messagingOptions.Value;
            _sendMessageService = sendMessageService;
            _mapper             = mapper;
            _logger             = logger;

            _subscriptionClient
                = new SubscriptionClient(
                      _messagingOptions.ServiceBusConnectionString,
                      _messagingOptions.TopicNameToListen,
                      _messagingOptions.SubscriptionName);
        }
Пример #30
0
        public static MessagingOptions UseFileStorageBroker(
            this MessagingOptions options,
            Action <IMessageBroker> brokerAction = null,
            string messageScope = null,
            string section      = "naos:messaging:fileStorage")
        {
            EnsureArg.IsNotNull(options, nameof(options));
            EnsureArg.IsNotNull(options.Context, nameof(options.Context));

            var configuration = options.Context.Configuration.GetSection(section).Get <FileStorageConfiguration>();

            if (configuration?.Enabled == true)
            {
                options.Context.Services.AddScoped <IMessageBroker>(sp =>
                {
                    configuration.Folder = configuration.Folder.EmptyToNull() ?? Path.GetTempPath();
                    var broker           = new FileStorageMessageBroker(o => o
                                                                        .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                        .Tracer(sp.GetService <ITracer>())
                                                                        .Mediator((IMediator)sp.CreateScope().ServiceProvider.GetService(typeof(IMediator)))
                                                                        .HandlerFactory(new ServiceProviderMessageHandlerFactory(sp))
                                                                        .Storage(new FileStorageLoggingDecorator(
                                                                                     sp.GetRequiredService <ILoggerFactory>(),
                                                                                     new FolderFileStorage(s => s
                                                                                                           .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                                                           .Folder(configuration.Folder)
                                                                                                           .Serializer(new JsonNetSerializer()))))
                                                                        .ProcessDelay(configuration.ProcessDelay)
                                                                        .Subscriptions(sp.GetRequiredService <ISubscriptionMap>())
                                                                        .FilterScope(Environment.GetEnvironmentVariable(EnvironmentKeys.IsLocal).ToBool()
                                ? Environment.MachineName.Humanize().Dehumanize().ToLower()
                                : string.Empty)
                                                                        .MessageScope(messageScope));

                    brokerAction?.Invoke(broker);
                    return(broker);
                });

                options.Context.Messages.Add($"naos services builder: messaging added (broker={nameof(FileStorageMessageBroker)})");
            }
            else
            {
                throw new NaosException("no messaging filestorage is enabled");
            }

            return(options);
        }