Example #1
0
    public static SqlDialect Convert(this BuildSqlDialect sqlDialect, string schema = null)
    {
        switch (sqlDialect)
        {
        case BuildSqlDialect.MsSqlServer:
            var sqlServer = new SqlDialect.MsSqlServer();
            if (schema != null)
            {
                sqlServer.Schema = schema;
            }
            return(sqlServer);

        case BuildSqlDialect.MySql:
            return(new SqlDialect.MySql());

        case BuildSqlDialect.PostgreSql:
            var postgreSql = new SqlDialect.PostgreSql
            {
                JsonBParameterModifier = parameter =>
                {
                    var npgsqlParameter = (Npgsql.NpgsqlParameter)parameter;
                    npgsqlParameter.NpgsqlDbType = NpgsqlDbType.Jsonb;
                }
            };
            if (schema != null)
            {
                postgreSql.Schema = schema;
            }
            return(postgreSql);

        case BuildSqlDialect.Oracle:
            var oracle = new SqlDialect.Oracle();
            if (schema != null)
            {
                oracle.Schema = schema;
            }
            return(oracle);

        default:
            throw new Exception($"Unknown BuildSqlDialect: {sqlDialect}.");
        }
    }
    static async Task Main()
    {
        const string tablePrefix = "";

        Console.Title = "Samples.MultiTenant.Receiver";

        var endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Receiver");

        endpointConfiguration.LimitMessageProcessingConcurrencyTo(1);
        endpointConfiguration.UseTransport <LearningTransport>();

        #region DisablingOutboxCleanup

        var outboxSettings = endpointConfiguration.EnableOutbox();
        outboxSettings.DisableCleanup();

        #endregion

        var persistence = endpointConfiguration.UsePersistence <SqlPersistence>();
        persistence.SqlDialect <SqlDialect.MsSqlServer>();

        #region ConnectionFactory

        persistence.MultiTenantConnectionBuilder(tenantIdHeaderName: "tenant_id",
                                                 buildConnectionFromTenantData: tenantId =>
        {
            var connectionString = Connections.GetForTenant(tenantId);
            return(new SqlConnection(connectionString));
        });

        #endregion

        persistence.SubscriptionSettings().DisableCache();
        persistence.TablePrefix(tablePrefix);

        var pipeline = endpointConfiguration.Pipeline;

        pipeline.Register(new StoreTenantIdBehavior(), "Stores tenant ID in the session");
        pipeline.Register(new PropagateTenantIdBehavior(), "Propagates tenant ID to outgoing messages");

        var startableEndpoint = await Endpoint.Create(endpointConfiguration)
                                .ConfigureAwait(false);

        using (var connection = new SqlConnection(Connections.TenantA))
            using (var receiverDataContext = new ReceiverDataContext(connection))
            {
                await receiverDataContext.Database.EnsureCreatedAsync();
            }

        using (var connection = new SqlConnection(Connections.TenantB))
            using (var receiverDataContext = new ReceiverDataContext(connection))
            {
                await receiverDataContext.Database.EnsureCreatedAsync();
            }

        var dialect         = new SqlDialect.MsSqlServer();
        var scriptDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NServiceBus.Persistence.Sql", "MsSqlServer");

        #region CreateSchema

        await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.TenantA), scriptDirectory,
                                   shouldInstallOutbox : true,
                                   shouldInstallSagas : true,
                                   shouldInstallSubscriptions : false,
                                   shouldInstallTimeouts : false);

        await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.TenantB), scriptDirectory,
                                   shouldInstallOutbox : true,
                                   shouldInstallSagas : true,
                                   shouldInstallSubscriptions : false,
                                   shouldInstallTimeouts : false);

        #endregion

        var endpointInstance = await startableEndpoint.Start()
                               .ConfigureAwait(false);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        if (endpointInstance != null)
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
    static async Task Main()
    {
        const string tablePrefix = "";

        Console.Title = "Samples.MultiTenant.Receiver";

        var endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Receiver");

        endpointConfiguration.LimitMessageProcessingConcurrencyTo(1);
        endpointConfiguration.UseTransport <LearningTransport>();
        endpointConfiguration.EnableOutbox();

        var persistence = endpointConfiguration.UsePersistence <SqlPersistence>();

        persistence.SqlDialect <SqlDialect.MsSqlServer>();

        #region ConnectionFactory

        persistence.ConnectionBuilder(MultiTenantConnectionFactory.GetConnection);

        #endregion

        persistence.SubscriptionSettings().DisableCache();
        persistence.TablePrefix(tablePrefix);

        var pipeline = endpointConfiguration.Pipeline;

        #region ExtractTenantConnectionStringBehavior

        pipeline.Register(
            behavior: typeof(ExtractTenantConnectionStringBehavior),
            description: "Extracts tenant connection string based on tenant ID header.");

        #endregion

        pipeline.Register(new StoreTenantIdBehavior(), "Stores tenant ID in the session");
        pipeline.Register(new PropagateTenantIdBehavior(), "Propagates tenant ID to outgoing messages");

        var startableEndpoint = await Endpoint.Create(endpointConfiguration)
                                .ConfigureAwait(false);

        using (var connection = new SqlConnection(Connections.TenantA))
            using (var receiverDataContext = new ReceiverDataContext(connection))
            {
                await receiverDataContext.Database.EnsureCreatedAsync();
            }

        using (var connection = new SqlConnection(Connections.TenantB))
            using (var receiverDataContext = new ReceiverDataContext(connection))
            {
                await receiverDataContext.Database.EnsureCreatedAsync();
            }

        var dialect         = new SqlDialect.MsSqlServer();
        var scriptDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NServiceBus.Persistence.Sql", "MsSqlServer");

        #region CreateSchema

        await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.TenantA), scriptDirectory,
                                   shouldInstallOutbox : false,
                                   shouldInstallSagas : true,
                                   shouldInstallSubscriptions : false,
                                   shouldInstallTimeouts : false);

        await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.TenantB), scriptDirectory,
                                   shouldInstallOutbox : false,
                                   shouldInstallSagas : true,
                                   shouldInstallSubscriptions : false,
                                   shouldInstallTimeouts : false);

        await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.Shared), scriptDirectory,
                                   shouldInstallOutbox : true,
                                   shouldInstallSagas : false,
                                   shouldInstallSubscriptions : false,
                                   shouldInstallTimeouts : true);

        #endregion

        #region Synonyms

        var sql = @"
if exists (select * from sys.synonyms where [name] = 'OutboxData')
   return;

create synonym OutboxData FOR [SqlMultiTenantReceiver].[dbo].[OutboxData]";
        SqlHelper.ExecuteSql(Connections.TenantA, sql);
        SqlHelper.ExecuteSql(Connections.TenantB, sql);

        #endregion

        var endpointInstance = await startableEndpoint.Start()
                               .ConfigureAwait(false);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        if (endpointInstance != null)
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }