/// <summary>
        /// Called when the features is activated
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        protected override void Setup(FeatureConfigurationContext context)
        {
            TimeoutClassMaps.ConfigureClassMaps();

            context.Container.ConfigureComponent<MongoTimeoutPersister>(DependencyLifecycle.SingleInstance)
                .ConfigureProperty(x => x.EndpointName, context.Settings.EndpointName());
        }
示例#2
0
        void SetTransportThresholds(FeatureConfigurationContext context)
        {
            var transportConfig = context.Settings.GetConfigSection<TransportConfig>();
            var maximumThroughput = 0;
            var maximumNumberOfRetries = 5;
            var maximumConcurrencyLevel = 1;

            if (transportConfig != null)
            {
                maximumNumberOfRetries = transportConfig.MaxRetries;
                maximumThroughput = transportConfig.MaximumMessageThroughputPerSecond;
                maximumConcurrencyLevel = transportConfig.MaximumConcurrencyLevel;
            }

            var transactionSettings = new TransactionSettings(context.Settings)
            {
                MaxRetries = maximumNumberOfRetries
            };

            context.Container.ConfigureComponent(b => new TransportReceiver(transactionSettings, maximumConcurrencyLevel, maximumThroughput, b.Build<IDequeueMessages>(), b.Build<IManageMessageFailures>(), context.Settings, b.Build<Configure>())
            {
                CriticalError = b.Build<CriticalError>(),
                Notifications = b.Build<BusNotifications>()
            }, DependencyLifecycle.InstancePerCall);
        }
        /// <summary>
        /// Called when the feature should perform its initialization. This call will only happen if the feature is enabled.
        /// </summary>
        protected override void Setup(FeatureConfigurationContext context)
        {
            context.Settings.Get<SharedMappings>()
                .AddMapping(ApplyMappings);

            context.Container.ConfigureComponent<OutboxPersister>(DependencyLifecycle.SingleInstance);
        }
示例#4
0
        /// <summary>
        /// See <see cref="Feature.Setup"/>
        /// </summary>
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            var processorAddress = context.Settings.LocalAddress().SubScope("Retries");
            var useRemoteRetryProcessor = context.Settings.HasSetting("SecondLevelRetries.AddressOfRetryProcessor");
            
            if (useRemoteRetryProcessor)
            {
                processorAddress = context.Settings.Get<Address>("SecondLevelRetries.AddressOfRetryProcessor");
            }

            var container = context.Container;
            container.ConfigureProperty<FaultManager>(fm => fm.RetriesErrorQueue, processorAddress);
            container.ConfigureProperty<SecondLevelRetriesProcessor>(rs => rs.InputAddress, processorAddress);
            var retryPolicy = context.Settings.GetOrDefault<Func<TransportMessage, TimeSpan>>("SecondLevelRetries.RetryPolicy");
            if (retryPolicy != null)
            {
                container.ConfigureProperty<SecondLevelRetriesProcessor>(rs => rs.RetryPolicy, retryPolicy);
            }
            container.ConfigureProperty<SecondLevelRetriesProcessor>(rs => rs.Disabled, useRemoteRetryProcessor); 
    
            var retriesConfig = context.Settings.GetConfigSection<SecondLevelRetriesConfig>();
            if (retriesConfig == null)
                return;

            container.ConfigureProperty<SecondLevelRetriesProcessor>(rs => rs.NumberOfRetries, retriesConfig.NumberOfRetries); 

            if (retriesConfig.TimeIncrease != TimeSpan.MinValue)
            {
                container.ConfigureProperty<SecondLevelRetriesProcessor>(rs => rs.TimeIncrease, retriesConfig.TimeIncrease); 
            }
        }
示例#5
0
        /// <summary>
        /// See <see cref="Feature.Setup"/>
        /// </summary>
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            // If Audit feature is enabled and the value not specified via config and instead specified in the registry:
            // Log a warning when running in the debugger to remind user to make sure the 
            // production machine will need to have the required registry setting.
            if (Debugger.IsAttached && GetAuditQueueAddressFromAuditConfig(context) == Address.Undefined)
            {
                Logger.Warn("Endpoint auditing is configured using the registry on this machine, please ensure that you either run Set-NServiceBusLocalMachineSettings cmdlet on the target deployment machine or specify the QueueName attribute in the AuditConfig section in your app.config file. To quickly add the AuditConfig section to your app.config, in Package Manager Console type: add-NServiceBusAuditConfig.");
            }

            context.Pipeline.Register<AuditBehavior.Registration>();

            var auditQueue = GetConfiguredAuditQueue(context);

            context.Container.ConfigureComponent<AuditQueueCreator>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(p => p.Enabled, true)
                .ConfigureProperty(t => t.AuditQueue, auditQueue);

            var behaviorConfig = context.Container.ConfigureComponent<AuditBehavior>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(p => p.AuditQueue, auditQueue);



            var messageAuditingConfig = context.Settings.GetConfigSection<AuditConfig>();
            if (messageAuditingConfig != null && messageAuditingConfig.OverrideTimeToBeReceived > TimeSpan.Zero)
            {
                behaviorConfig.ConfigureProperty(t => t.TimeToBeReceivedOnForwardedMessages, messageAuditingConfig.OverrideTimeToBeReceived);
            }
        }
        /// <summary>
        /// Invoked if the feature is activated
        /// </summary>
        /// <param name="context">The feature context</param>
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            var queueName = context.Settings.GetOrDefault<string>("MsmqSubscriptionPersistence.QueueName");

            var cfg = context.Settings.GetConfigSection<MsmqSubscriptionStorageConfig>();

            if (string.IsNullOrEmpty(queueName))
            {
                if (cfg == null)
                {
                    Logger.Warn("Could not find configuration section for Msmq Subscription Storage and no name was specified for this endpoint. Going to default the subscription queue");
                    queueName = "NServiceBus.Subscriptions"; 
                }
                else
                {
                    queueName = cfg.Queue;
                }
            }

            var storageQueue = Address.Parse(queueName);

            context.Container.ConfigureComponent<SubscriptionsQueueCreator>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(t => t.StorageQueue, storageQueue);

            context.Container.ConfigureComponent<MsmqSubscriptionStorage>(DependencyLifecycle.SingleInstance)
                .ConfigureProperty(s => s.Queue, storageQueue)
                .ConfigureProperty(s => s.TransactionsEnabled, context.Settings.Get<bool>("Transactions.Enabled"));
        }
 protected override void Setup(FeatureConfigurationContext context)
 {
     PipelineSettings pipeline = context.Pipeline;
     pipeline.Replace("NServiceBus.DeserializeLogicalMessagesConnector", typeof(DeserializeConnector));
     pipeline.Replace("NServiceBus.SerializeMessageConnector", typeof(SerializeConnector));
     context.Container.ConfigureComponent<SerializationMapper>(DependencyLifecycle.SingleInstance);
 }
示例#8
0
        static bool RequireOutboxConsent(FeatureConfigurationContext context)
        {
            if (context.Settings.GetOrDefault<bool>("DisableOutboxTransportCheck"))
            {
                return true;
            }
            var configValue = ConfigurationManager.AppSettings.Get("NServiceBus/Outbox");

            if (configValue == null)
            {
                throw new Exception(@"To use the Outbox feature with MSMQ or SQLServer transports it must be enabled in the config file.
To do that add the following:
<appSettings>
    <add key=""NServiceBus/Outbox"" value=""true""/>
</appSettings>

The reason this is required is to ensure that all the guidelines regarding this feature have been understood and know the limitations when running under MSMQ or SQLServer transports.");
            }

            bool result;

            if (!bool.TryParse(configValue, out result))
            {
                throw new Exception("Invalid value in \"NServiceBus/Outbox\" AppSetting. Ensure it is either \"true\" or \"false\".");
            }

            return result;
        }
示例#9
0
        static bool RequireOutboxConsent(FeatureConfigurationContext context)
        {
            if (context.Settings.GetOrDefault<bool>("DisableOutboxTransportCheck"))
            {
                return true;
            }
            var configValue = ConfigurationManager.AppSettings.Get("NServiceBus/Outbox");

            if (configValue == null)
            {
                throw new Exception(@"To use the Outbox feature with MSMQ or SQLServer transports you need to enable it in your config file.
To do that add the following:
<appSettings>
    <add key=""NServiceBus/Outbox"" value=""true""/>
</appSettings>

The reason you need to do this is because we need to ensure that you have read all the documentation regarding this feature and know the limitations when running it under MSMQ or SQLServer transports.");
            }

            bool result;

            if (!Boolean.TryParse(configValue, out result))
            {
                throw new Exception("Invalid value in \"NServiceBus/Outbox\" AppSetting. Please ensure it is either \"true\" or \"false\".");
            }

            return result;
        }
示例#10
0
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            context.Pipeline.Register("TransportReceiveToPhysicalMessageProcessingConnector", b => b.Build<TransportReceiveToPhysicalMessageProcessingConnector>(), "Allows to abort processing the message");
            context.Pipeline.Register("LoadHandlersConnector", b => b.Build<LoadHandlersConnector>(), "Gets all the handlers to invoke from the MessageHandler registry based on the message type.");

            var hasUnitsOfWork = context.Container.HasComponent<IManageUnitsOfWork>();
            context.Pipeline.Register("ExecuteUnitOfWork", new UnitOfWorkBehavior(hasUnitsOfWork), "Executes the UoW");

            var hasIncomingTransportMessageMutators = context.Container.HasComponent<IMutateIncomingTransportMessages>();
            context.Pipeline.Register("MutateIncomingTransportMessage", new MutateIncomingTransportMessageBehavior(hasIncomingTransportMessageMutators), "Executes IMutateIncomingTransportMessages");

            var hasIncomingMessageMutators = context.Container.HasComponent<IMutateIncomingMessages>();
            context.Pipeline.Register("MutateIncomingMessages", new MutateIncomingMessageBehavior(hasIncomingMessageMutators), "Executes IMutateIncomingMessages");

            context.Pipeline.Register("InvokeHandlers", new InvokeHandlerTerminator(), "Calls the IHandleMessages<T>.Handle(T)");

            context.Container.ConfigureComponent(b =>
            {
                var storage = context.Container.HasComponent<IOutboxStorage>() ? b.Build<IOutboxStorage>() : new NoOpOutbox();

                return new TransportReceiveToPhysicalMessageProcessingConnector(storage);
            }, DependencyLifecycle.InstancePerCall);

            context.Container.ConfigureComponent(b =>
            {
                var adapter = context.Container.HasComponent<ISynchronizedStorageAdapter>() ? b.Build<ISynchronizedStorageAdapter>() : new NoOpAdaper();
                var syncStorage = context.Container.HasComponent<ISynchronizedStorage>() ? b.Build<ISynchronizedStorage>() : new NoOpSynchronizedStorage();

                return new LoadHandlersConnector(b.Build<MessageHandlerRegistry>(), syncStorage, adapter);
            }, DependencyLifecycle.InstancePerCall);
        }
        /// <summary>
        /// Initializes a new instance of <see cref="ConfigureTransport"/>.
        /// </summary>
        protected override void Configure(FeatureConfigurationContext context, string connectionString)
        {
            new CheckMachineNameForComplianceWithDtcLimitation()
            .Check();
            context.Container.ConfigureComponent<CorrelationIdMutatorForBackwardsCompatibilityWithV3>(DependencyLifecycle.InstancePerCall);
            context.Container.ConfigureComponent<MsmqUnitOfWork>(DependencyLifecycle.SingleInstance);
            context.Container.ConfigureComponent<MsmqDequeueStrategy>(DependencyLifecycle.InstancePerCall);

            var cfg = context.Settings.GetConfigSection<MsmqMessageQueueConfig>();

            var settings = new MsmqSettings();
            if (cfg != null)
            {
                settings.UseJournalQueue = cfg.UseJournalQueue;
                settings.UseDeadLetterQueue = cfg.UseDeadLetterQueue;

                Logger.Warn(Message);
            }
            else
            {
                if (connectionString != null)
                {
                    settings = new MsmqConnectionStringBuilder(connectionString).RetrieveSettings();
                }
            }

            context.Container.ConfigureComponent<MsmqMessageSender>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(t => t.Settings, settings)
                .ConfigureProperty(t => t.SuppressDistributedTransactions, context.Settings.Get<bool>("Transactions.SuppressDistributedTransactions"));

            context.Container.ConfigureComponent<MsmqQueueCreator>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(t => t.Settings, settings);
        }
示例#12
0
        /// <summary>
        /// See <see cref="Feature.Setup" />.
        /// </summary>
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            context.Pipeline.Register(new AuditToDispatchConnector(auditConfig.TimeToBeReceived), "Dispatches the audit message to the transport");
            context.Pipeline.Register("AuditProcessedMessage", new InvokeAuditPipelineBehavior(auditConfig.Address), "Execute the audit pipeline");

            context.Settings.Get<QueueBindings>().BindSending(auditConfig.Address);
        }
    protected override void Setup(FeatureConfigurationContext context)
    {
        context.Pipeline.Replace(WellKnownStep.DeserializeMessages, typeof(DeserializeBehavior));
        context.Pipeline.Replace(WellKnownStep.SerializeMessage, typeof(SerializeBehavior));

        context.Container.ConfigureComponent<SerializationMapper>(DependencyLifecycle.SingleInstance);
    }
示例#14
0
        bool VerifyPrerequisite(FeatureConfigurationContext context)
        {
            var encryptedProperties = GetEncryptedProperties(context);
            var encryptionServiceConstructorDefined = context.Settings.GetEncryptionServiceConstructor(out serviceConstructor);
            var encryptionPropertiesFound = encryptedProperties.Any();
            if (encryptionPropertiesFound)
            {
                if (!encryptionServiceConstructorDefined)
                {
                    var stringBuilder = new StringBuilder("Encrypted properties were found but no encryption service has been defined. Please call ConfigurationBuilder.RijndaelEncryptionService or ConfigurationBuilder.RegisterEncryptionService. Encrypted properties: ");
                    foreach (var encryptedProperty in encryptedProperties)
                    {
                        stringBuilder.AppendFormat("{0}.{1}\r\n", encryptedProperty.DeclaringType, encryptedProperty.Name);
                    }
                    throw new Exception(stringBuilder.ToString());
                }
            }
            else
            {
                if (encryptionServiceConstructorDefined)
                {
                    var message = 
@"You have configured a encryption service via either ConfigurationBuilder.RijndaelEncryptionService or ConfigurationBuilder.RegisterEncryptionService however no properties were found on type that require encryption. 
Perhaps you forgot to define your encryption message conventions or to define message properties using as WireEncryptedString.";
                    log.Warn(message);
                }
            }
            return encryptionPropertiesFound;
        }
        public override void Configure(FeatureConfigurationContext context, string connectionStringWithSchema)
        {
            context.Pipeline.Register<ReadIncomingCallbackAddressBehavior.Registration>();

            var useCallbackReceiver = context.Settings.Get<bool>(UseCallbackReceiverSettingKey);
            var maxConcurrencyForCallbackReceiver = context.Settings.Get<int>(MaxConcurrencyForCallbackReceiverSettingKey);
            var queueName = context.Settings.EndpointName();
            var callbackQueue = string.Format("{0}.{1}", queueName, RuntimeEnvironment.MachineName);
            if (useCallbackReceiver)
            {
                var callbackAddress = Address.Parse(callbackQueue);

                context.Container.ConfigureComponent<CallbackQueueCreator>(DependencyLifecycle.InstancePerCall)
                    .ConfigureProperty(p => p.Enabled, true)
                    .ConfigureProperty(p => p.CallbackQueueAddress, callbackAddress);

                context.Pipeline.Register<SetOutgoingCallbackAddressBehavior.Registration>();
                context.Container.ConfigureComponent(c => new OutgoingCallbackAddressSetter(callbackQueue), DependencyLifecycle.SingleInstance);
            }
            context.Container.RegisterSingleton(new SecondaryReceiveConfiguration(workQueue =>
            {
                //if this isn't the main queue we shouldn't use callback receiver
                if (!useCallbackReceiver || workQueue != queueName)
                {
                    return SecondaryReceiveSettings.Disabled();
                }

                return SecondaryReceiveSettings.Enabled(callbackQueue, maxConcurrencyForCallbackReceiver);
            }));
        }
        protected override void Configure(FeatureConfigurationContext context, string connectionStringWithSchema)
        {
            //Until we refactor the whole address system
            Address.IgnoreMachineName();

            if (String.IsNullOrEmpty(connectionStringWithSchema))
            {
                throw new ArgumentException("Sql Transport connection string cannot be empty or null.");
            }

            foreach (var config in configs)
            {
                config.Configure(context, connectionStringWithSchema);
            }

            context.Container.ConfigureComponent(
                b => new SqlServerMessageSender(
                    b.Build<IConnectionStringProvider>(),
                    new ContextualConnectionStore(b.Build<PipelineExecutor>()),
                    new ContextualCallbackAddressStore(b.Build<PipelineExecutor>().CurrentContext),
                    b.Build<ConnectionFactory>()),
                DependencyLifecycle.InstancePerCall);

            if (!context.Settings.GetOrDefault<bool>("Endpoint.SendOnly"))
            {
                context.Container.ConfigureComponent<TransportNotifications>(DependencyLifecycle.SingleInstance);
                context.Container.ConfigureComponent<SqlServerQueueCreator>(DependencyLifecycle.InstancePerCall);

                var errorQueue = ErrorQueueSettings.GetConfiguredErrorQueue(context.Settings);
                context.Container.ConfigureComponent(b => new ReceiveStrategyFactory(new ContextualConnectionStore(b.Build<PipelineExecutor>()), b.Build<LocalConnectionParams>(), errorQueue, b.Build<ConnectionFactory>()), DependencyLifecycle.InstancePerCall);

                context.Container.ConfigureComponent<SqlServerPollingDequeueStrategy>(DependencyLifecycle.InstancePerCall);
                context.Container.ConfigureComponent(b => new SqlServerStorageContext(b.Build<PipelineExecutor>(), b.Build<LocalConnectionParams>()), DependencyLifecycle.InstancePerUnitOfWork);
            }
        }
示例#17
0
        /// <summary>
        /// See <see cref="Feature.Setup"/>
        /// </summary>
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            context.Container.ConfigureComponent<MessageMapper>(DependencyLifecycle.SingleInstance);
            var c = context.Container.ConfigureComponent<XmlMessageSerializer>(DependencyLifecycle.SingleInstance);

            context.Settings.ApplyTo<XmlMessageSerializer>((IComponentConfig)c);
        }
示例#18
0
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            try
            {
                var licenseManager = new LicenseManager();
                licenseManager.InitializeLicense(context.Settings.Get<string>(LicenseTextSettingsKey));

                context.Container.RegisterSingleton(licenseManager);

                var licenseExpired = licenseManager.HasLicenseExpired();
                if (!licenseExpired)
                {
                    return;
                }

                context.Pipeline.Register("LicenseReminder", new AuditInvalidLicenseBehavior(), "Audits that the message was processed by an endpoint with an expired license");

                if (Debugger.IsAttached)
                {
                    context.Pipeline.Register("LogErrorOnInvalidLicense", new LogErrorOnInvalidLicenseBehavior(), "Logs an error when running in debug mode with an expired license");
                }
            }
            catch (Exception ex)
            {
                //we only log here to prevent licensing issue to abort startup and cause production outages
                Logger.Fatal("Failed to initialize the license", ex);
            }
        }
示例#19
0
        /// <summary>
        ///     See <see cref="Feature.Setup" />
        /// </summary>
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            // Register the Saga related behavior for incoming messages
            context.Pipeline.Register<SagaPersistenceBehavior.SagaPersistenceRegistration>();

            context.Container.RegisterSingleton(sagaConfigurationCache);

            foreach (var t in context.Settings.GetAvailableTypes())
            {
                if (IsSagaType(t))
                {
                    context.Container.ConfigureComponent(t, DependencyLifecycle.InstancePerCall);
                    ConfigureSaga(t, conventions);
                    continue;
                }

                if (IsFinderType(t))
                {
                    context.Container.ConfigureComponent(t, DependencyLifecycle.InstancePerCall);
                    ConfigureFinder(t, conventions);
                    continue;
                }

                if (IsSagaNotFoundHandler(t))
                {
                    context.Container.ConfigureComponent(t, DependencyLifecycle.InstancePerCall);
                }
            }

            CreateAdditionalFindersAsNecessary(context);
        }
    protected override void Setup(FeatureConfigurationContext context)
    {
        context.Settings.EnableFeature<StorageType.Sagas>();

        var settings = context.Settings;
        var endpointName = settings.GetTablePrefix<StorageType.Sagas>();
        var sqlVarient = settings.GetSqlVarient();
        var commandBuilder = new SagaCommandBuilder(sqlVarient,endpointName);
        var jsonSerializerSettings = SagaSettings.GetJsonSerializerSettings(settings);
        var jsonSerializer = BuildJsonSerializer(jsonSerializerSettings);
        var readerCreator = SagaSettings.GetReaderCreator(settings);
        if (readerCreator == null)
        {
            readerCreator = reader => new JsonTextReader(reader);
        }
        var writerCreator = SagaSettings.GetWriterCreator(settings);
        if (writerCreator == null)
        {
            writerCreator = writer => new JsonTextWriter(writer);
        }
        var versionDeserializeBuilder = SagaSettings.GetVersionSettings(settings);
        var infoCache = new SagaInfoCache(versionDeserializeBuilder, jsonSerializer, readerCreator, writerCreator, commandBuilder);
        var sagaPersister = new SagaPersister(infoCache);
        context.Container.ConfigureComponent<ISagaPersister>(() => sagaPersister, DependencyLifecycle.SingleInstance);
    }
示例#21
0
        /// <summary>
        /// See <see cref="Feature.Setup"/>
        /// </summary>
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            context.Container.ConfigureComponent<AutoSubscriptionStrategy>(DependencyLifecycle.InstancePerCall);

            var transportDefinition = context.Settings.Get<TransportDefinition>();

            //if the transport has centralized pubsub we can auto-subscribe all events regardless if they have explicit routing or not
            if (transportDefinition != null && transportDefinition.HasSupportForCentralizedPubSub)
            {
                context.Container.ConfigureProperty<AutoSubscriptionStrategy>(s => s.DoNotRequireExplicitRouting, true);
            }

            //apply any user specific settings
            var targetType = typeof(AutoSubscriptionStrategy);

            foreach (var property in targetType.GetProperties())
            {
                var settingsKey = targetType.FullName + "." + property.Name;

                if (context.Settings.HasSetting(settingsKey))
                {
                    context.Container.ConfigureProperty<AutoSubscriptionStrategy>(property.Name, context.Settings.Get(settingsKey));
                }
            }
        }
        /// <summary>
        /// Called when the feature should perform its initialization. This call will only happen if the feature is enabled.
        /// </summary>
        protected override void Setup(FeatureConfigurationContext context)
        {
            context.Settings.Get<SharedMappings>()
                .AddMapping(c => ApplyMappings(context.Settings,c));

            context.Container.ConfigureComponent<SagaPersister>(DependencyLifecycle.InstancePerCall);
        }
示例#23
0
        void EnableBestPracticeEnforcement(FeatureConfigurationContext context)
        {
            var validations = new Validations(context.Settings.Get<Conventions>());

            context.Pipeline.Register(
                "EnforceSendBestPractices",
                new EnforceSendBestPracticesBehavior(validations),
                "Enforces send messaging best practices");

            context.Pipeline.Register(
                "EnforceReplyBestPractices",
                new EnforceReplyBestPracticesBehavior(validations),
                "Enforces reply messaging best practices");

            context.Pipeline.Register(
                "EnforcePublishBestPractices",
                new EnforcePublishBestPracticesBehavior(validations),
                "Enforces publish messaging best practices");

            context.Pipeline.Register(
                "EnforceSubscribeBestPractices",
                new EnforceSubscribeBestPracticesBehavior(validations),
                "Enforces subscribe messaging best practices");

            context.Pipeline.Register(
                "EnforceUnsubscribeBestPractices",
                new EnforceUnsubscribeBestPracticesBehavior(validations),
                "Enforces unsubscribe messaging best practices");
        }
示例#24
0
        /// <summary>
        /// See <see cref="Feature.Setup" />.
        /// </summary>
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            if (!PersistenceStartup.HasSupportFor<StorageType.Sagas>(context.Settings))
            {
                throw new Exception("The selected persistence doesn't have support for saga storage. Select another persistence or disable the sagas feature using endpointConfiguration.DisableFeature<Sagas>()");
            }

            var sagaMetaModel = context.Settings.Get<SagaMetadataCollection>();
            sagaMetaModel.Initialize(context.Settings.GetAvailableTypes(), conventions);

            RegisterCustomFindersInContainer(context.Container, sagaMetaModel);

            foreach (var t in context.Settings.GetAvailableTypes())
            {
                if (IsSagaNotFoundHandler(t))
                {
                    context.Container.ConfigureComponent(t, DependencyLifecycle.InstancePerCall);
                }
            }

            // Register the Saga related behaviors for incoming messages
            context.Pipeline.Register("InvokeSaga", b => new SagaPersistenceBehavior(b.Build<ISagaPersister>(), b.Build<ICancelDeferredMessages>(), sagaMetaModel), "Invokes the saga logic");
            context.Pipeline.Register("InvokeSagaNotFound", new InvokeSagaNotFoundBehavior(), "Invokes saga not found logic");
            context.Pipeline.Register("AttachSagaDetailsToOutGoingMessage", new AttachSagaDetailsToOutGoingMessageBehavior(), "Makes sure that outgoing messages have saga info attached to them");
        }
示例#25
0
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            var defaultAddress = context.Settings.LocalAddress();
            var hostInfo = new HostInformation(context.Settings.Get<Guid>("NServiceBus.HostInformation.HostId"), 
                context.Settings.Get<string>("NServiceBus.HostInformation.DisplayName"), 
                context.Settings.Get<Dictionary<string, string>>("NServiceBus.HostInformation.Properties"));
            
            context.Container.ConfigureComponent<Unicast.UnicastBus>(DependencyLifecycle.SingleInstance)
                .ConfigureProperty(u => u.InputAddress, defaultAddress)
                .ConfigureProperty(u => u.HostInformation, hostInfo);

            ConfigureSubscriptionAuthorization(context);

            context.Container.ConfigureComponent<PipelineExecutor>(DependencyLifecycle.SingleInstance);
            ConfigureBehaviors(context);

            var knownMessages = context.Settings.GetAvailableTypes()
                .Where(context.Settings.Get<Conventions>().IsMessageType)
                .ToList();

            RegisterMessageOwnersAndBusAddress(context, knownMessages);

            ConfigureMessageRegistry(context, knownMessages);

            if (context.Settings.GetOrDefault<bool>("Endpoint.SendOnly"))
            {
                return;
            }

            SetTransportThresholds(context);
        }
        /// <summary>
        ///     Called when the feature should perform its initialization. This call will only happen if the feature is enabled.
        /// </summary>
        protected override void Setup(FeatureConfigurationContext context)
        {
            // TODO here would be the place to wire up the ISagaFinder extension point

            context.Container.ConfigureComponent<SagaPersister>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(p => p.AllowUnsafeLoads, context.Settings.GetOrDefault<bool>(RavenDbSagaSettingsExtensions.AllowStaleSagaReadsKey));
        }
        /// <summary>
        /// Called when the feature should perform its initialization. This call will only happen if the feature is enabled.
        /// </summary>
        protected override void Setup(FeatureConfigurationContext context)
        {            
            var configuration = context.Settings.GetOrDefault<Configuration>("NHibernate.Subscriptions.Configuration") ?? context.Settings.GetOrDefault<Configuration>("StorageConfiguration");

            if (configuration == null)
            {
                var properties = new ConfigureNHibernate(context.Settings).SubscriptionStorageProperties;
                configuration = new Configuration().SetProperties(properties);
            }
            ConfigureNHibernate.ThrowIfRequiredPropertiesAreMissing(configuration.Properties);

            ConfigureNHibernate.AddMappings<SubscriptionMap>(configuration);

            context.Container.ConfigureComponent<Unicast.Subscriptions.NHibernate.Installer.Installer>(DependencyLifecycle.SingleInstance)
                .ConfigureProperty(x => x.Configuration, configuration)
                .ConfigureProperty(x => x.RunInstaller, RunInstaller(context));

            var sessionSource = new SubscriptionStorageSessionProvider(configuration.BuildSessionFactory());

            context.Container.RegisterSingleton(sessionSource);

            if (context.Settings.HasSetting("NHibernate.Subscriptions.CacheExpiration"))
            {
                context.Container.RegisterSingleton<ISubscriptionStorage>(new CachedSubscriptionPersister(sessionSource, context.Settings.Get<TimeSpan>("NHibernate.Subscriptions.CacheExpiration")));
            }
            else
            {
                context.Container.ConfigureComponent<SubscriptionPersister>(DependencyLifecycle.InstancePerCall);
            }
        }
示例#28
0
 /// <summary>
 /// Invoked if the feature is activated
 /// </summary>
 /// <param name="context">The feature context</param>
 protected internal override void Setup(FeatureConfigurationContext context)
 {
     foreach (var installerType in GetInstallerTypes(context))
     {
         context.Container.ConfigureComponent(installerType, DependencyLifecycle.InstancePerCall);
     }
 }
        /// <summary>
        /// Called when the feature should perform its initialization. This call will only happen if the feature is enabled.
        /// </summary>
        protected override void Setup(FeatureConfigurationContext context)
        {
            var configuration = context.Settings.GetOrDefault<Configuration>("StorageConfiguration");

            if (configuration == null)
            {
                var properties = new ConfigureNHibernate(context.Settings).SagaPersisterProperties;
                configuration = new Configuration().SetProperties(properties);
            }
            ConfigureNHibernate.ThrowIfRequiredPropertiesAreMissing(configuration.Properties);

            context.Settings.Get<SharedMappings>().ApplyTo(configuration);

            string connString;

            if (!configuration.Properties.TryGetValue(Environment.ConnectionString, out connString))
            {
                string connStringName;

                if (configuration.Properties.TryGetValue(Environment.ConnectionStringName, out connStringName))
                {
                    var connectionStringSettings = System.Configuration.ConfigurationManager.ConnectionStrings[connStringName];

                    connString = connectionStringSettings.ConnectionString;
                }
            }

            context.Container.RegisterSingleton(new SessionFactoryProvider(configuration.BuildSessionFactory()));

            var disableConnectionSharing = DisableTransportConnectionSharing(context);

            context.Container
                .ConfigureProperty<DbConnectionProvider>(p => p.DisableConnectionSharing, disableConnectionSharing)
                .ConfigureProperty<DbConnectionProvider>(p => p.DefaultConnectionString, connString);

            context.Pipeline.Register<OpenSqlConnectionBehavior.Registration>();
            context.Pipeline.Register<OpenSessionBehavior.Registration>();

            context.Container.ConfigureComponent<OpenSqlConnectionBehavior>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(p => p.ConnectionString, connString)
                .ConfigureProperty(p => p.DisableConnectionSharing, disableConnectionSharing);

            context.Container.ConfigureComponent<OpenSessionBehavior>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(p => p.ConnectionString, connString)
                .ConfigureProperty(p => p.DisableConnectionSharing, disableConnectionSharing)
                .ConfigureProperty(p => p.SessionCreator, context.Settings.GetOrDefault<Func<ISessionFactory, string, ISession>>("NHibernate.SessionCreator"));

            context.Container.ConfigureComponent(b => new NHibernateStorageContext(b.Build<PipelineExecutor>(), connString), DependencyLifecycle.InstancePerUnitOfWork);
            context.Container.ConfigureComponent<SharedConnectionStorageSessionProvider>(DependencyLifecycle.SingleInstance)
                .ConfigureProperty(p => p.ConnectionString, connString);

            if (context.Settings.GetOrDefault<bool>("NHibernate.RegisterManagedSession"))
            {
                context.Container.ConfigureComponent(b => b.Build<NHibernateStorageContext>().Session, DependencyLifecycle.InstancePerCall);
            }

            context.Container.ConfigureComponent<Installer>(DependencyLifecycle.SingleInstance)
                .ConfigureProperty(x => x.Configuration, configuration)
                .ConfigureProperty(x => x.RunInstaller, context.Settings.Get<bool>("NHibernate.Common.AutoUpdateSchema"));
        }
示例#30
0
        static void ConfigureSender(FeatureConfigurationContext context, Address gatewayInputAddress)
        {
            if (!context.Container.HasComponent<IForwardMessagesToSites>())
            {
                context.Container.ConfigureComponent<SingleCallChannelForwarder>(DependencyLifecycle.InstancePerCall);
            }

            context.Container.ConfigureComponent<MessageNotifier>(DependencyLifecycle.SingleInstance);
            context.Container.ConfigureComponent<GatewaySender>(DependencyLifecycle.SingleInstance)
                .ConfigureProperty(t => t.InputAddress, gatewayInputAddress)
                .ConfigureProperty(t => t.Disabled, false);

            var configSection = context.Settings.GetConfigSection<GatewayConfig>();

            if (configSection != null && configSection.GetChannels().Any())
            {
                context.Container.ConfigureComponent<ConfigurationBasedChannelManager>(DependencyLifecycle.SingleInstance)
                    .ConfigureProperty(c => c.ReceiveChannels, configSection.GetChannels());
            }
            else
            {
                context.Container.ConfigureComponent<ConventionBasedChannelManager>(DependencyLifecycle.SingleInstance)
                    .ConfigureProperty(t => t.EndpointName, context.Settings.EndpointName());
            }

            ConfigureSiteRouters(context);
        }