Exemple #1
0
            public When_pre_inserting_the_state_machine_instance_using_ef()
            {
                ISagaDbContextFactory <Instance> sagaDbContextFactory = new DelegateSagaDbContextFactory <Instance>(
                    () => new InstanceSagaDbContext(LocalDbConnectionStringProvider.GetLocalDbConnectionString()));

                _repository = EntityFrameworkSagaRepository <Instance> .CreatePessimistic(sagaDbContextFactory);
            }
Exemple #2
0
        public When_using_EntityFramework()
        {
            _sagaDbContextFactory = new DelegateSagaDbContextFactory <ShoppingChore>(
                () => new ShoppingChoreSagaDbContext(SagaDbContextFactoryProvider.GetLocalDbConnectionString()));

            _repository = new Lazy <ISagaRepository <ShoppingChore> >(() => EntityFrameworkSagaRepository <ShoppingChore> .CreatePessimistic(_sagaDbContextFactory));
        }
Exemple #3
0
            public When_pre_inserting_in_an_invalid_state_using_ef()
            {
                var sagaDbContextFactory =
                    new DelegateSagaDbContextFactory <Instance>(() => new InstanceSagaDbContext(SagaDbContextFactoryProvider.GetLocalDbConnectionString()));

                _repository = EntityFrameworkSagaRepository <Instance> .CreatePessimistic(sagaDbContextFactory);
            }
        public Locating_an_existing_ef_saga()
        {
            var sagaDbContextFactory = new DelegateSagaDbContextFactory <SimpleSaga>(() =>
                                                                                     new SimpleSagaDbContext(LocalDbConnectionStringProvider.GetLocalDbConnectionString()));

            _sagaRepository = new Lazy <ISagaRepository <SimpleSaga> >(() => EntityFrameworkSagaRepository <SimpleSaga> .CreatePessimistic(sagaDbContextFactory));
        }
Exemple #5
0
 public When_using_EntityFrameworkConcurrencyPessimistic()
 {
     _sagaDbContextFactory = new DelegateSagaDbContextFactory <ChoirStatePessimistic>(() =>
                                                                                      new ChoirStatePessimisticSagaDbContext(SagaDbContextFactoryProvider.GetLocalDbConnectionString()));
     _repository = new Lazy <ISagaRepository <ChoirStatePessimistic> >(() =>
                                                                       EntityFrameworkSagaRepository <ChoirStatePessimistic> .CreatePessimistic(_sagaDbContextFactory));
 }
        public static void UseEntityFrameworkCoreSagaRepository(this IJobServiceConfigurator configurator, Func<JobServiceSagaDbContext> contextFactory,
            ILockStatementProvider lockStatementProvider = default)
        {
            configurator.Repository = EntityFrameworkSagaRepository<JobTypeSaga>.CreatePessimistic(contextFactory, lockStatementProvider);

            configurator.JobRepository = EntityFrameworkSagaRepository<JobSaga>.CreatePessimistic(contextFactory, lockStatementProvider);

            configurator.JobAttemptRepository = EntityFrameworkSagaRepository<JobAttemptSaga>.CreatePessimistic(contextFactory, lockStatementProvider);
        }
Exemple #7
0
 public Locating_an_existing_ef_saga()
 {
     // add new migration by calling
     // dotnet ef migrations add --context "SagaDbContext``2" Init  -v
     _sagaRepository = new Lazy <ISagaRepository <SimpleSaga> >(() =>
                                                                EntityFrameworkSagaRepository <SimpleSaga> .CreatePessimistic(
                                                                    () => new SimpleSagaContextFactory().CreateDbContext(DbContextOptionsBuilder),
                                                                    RawSqlLockStatements));
 }
 public Using_custom_include_in_repository()
 {
     // // add new migration by calling
     // // dotnet ef migrations add --context "SagaDbContext``2" Init  -v
     _sagaRepository = new Lazy <ISagaRepository <SagaWithDependency> >(() =>
                                                                        EntityFrameworkSagaRepository <SagaWithDependency> .CreatePessimistic(
                                                                            () => new SagaWithDependencyContextFactory().CreateDbContext(DbContextOptionsBuilder),
                                                                            RawSqlLockStatements,
                                                                            queryable => queryable.Include(it => it.Dependency).ThenInclude(dependency => dependency.SagaInnerDependency)));
 }
Exemple #9
0
        static async Task Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));

            var builder = new HostBuilder()
                          .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: true);
                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
                          .ConfigureServices((hostContext, services) =>
            {
                services.Configure <AppConfig>(options => hostContext.Configuration.GetSection("AppConfig").Bind(options));

                services.AddMassTransit(cfg =>
                {
                    cfg.AddConsumersFromNamespaceContaining <ConsumerAnchor>();
                    cfg.AddSagaStateMachinesFromNamespaceContaining <StateMachineAnchor>();
                    cfg.AddActivitiesFromNamespaceContaining <ActivitiesAnchor>();
                    cfg.AddBus(ConfigureBus);
                });

                services.AddDbContext <DbContext, SampleBatchDbContext>(x => x.UseSqlServer(hostContext.Configuration.GetConnectionString("sample-batch")));

                services.AddSingleton(typeof(ISagaDbContextFactory <BatchState>), typeof(SagaScopedDbConnectionFactory <BatchState>));
                services.AddSingleton(typeof(ISagaDbContextFactory <JobState>), typeof(SagaScopedDbConnectionFactory <JobState>));

                // I specified the MsSqlLockStatements because in my State Entities EFCore EntityConfigurations, I changed the column name from CorrelationId, to "BatchId" and "BatchJobId"
                // Otherwise I could just use the default, which are "... WHERE CorrelationId = @p0"
                services.AddSingleton <ISagaRepository <BatchState> >(x => EntityFrameworkSagaRepository <BatchState> .CreatePessimistic(x.GetRequiredService <ISagaDbContextFactory <BatchState> >(), new MsSqlLockStatements(rowLockStatement: "select * from {0}.{1} WITH (UPDLOCK, ROWLOCK) WHERE BatchId = @p0")));
                services.AddSingleton <ISagaRepository <JobState> >(x => EntityFrameworkSagaRepository <JobState> .CreatePessimistic(x.GetRequiredService <ISagaDbContextFactory <JobState> >(), new MsSqlLockStatements(rowLockStatement: "select * from {0}.{1} WITH (UPDLOCK, ROWLOCK) WHERE BatchJobId = @p0")));

                services.AddSingleton <IHostedService, MassTransitConsoleHostedService>();
                services.AddSingleton <IHostedService, EfDbCreatedHostedService>();    // So we don't need to use ef migrations for this sample. Likely if you are going to deploy to a production environment, you want a better DB deploy strategy.
            })
                          .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
            });

            if (isService)
            {
                await builder.RunAsServiceAsync();
            }
            else
            {
                await builder.RunConsoleAsync();
            }
        }
        public SlowConcurrentSaga_Specs()
        {
            // rowlock statements that don't work to cause a deadlock.
            var notWorkingRowLockStatements = new SqlLockStatementProvider("dbo", "SELECT * FROM \"{1}\" WHERE \"CorrelationId\" = @p0");

            // add new migration by calling
            // dotnet ef migrations add --context "SagaDbContext``2" Init  -v
            _sagaRepository = new Lazy <ISagaRepository <SlowConcurrentSaga> >(() =>
                                                                               EntityFrameworkSagaRepository <SlowConcurrentSaga> .CreatePessimistic(
                                                                                   () => new SlowConcurrentSagaContextFactory().CreateDbContext(DbContextOptionsBuilder),
                                                                                   notWorkingRowLockStatements));

            _sagaTestHarness = BusTestHarness.StateMachineSaga(new SlowConcurrentSagaStateMachine(), _sagaRepository.Value);
        }
Exemple #11
0
        public Locating_an_existing_ef_saga()
        {
            // add new migration by calling
            // dotnet ef migrations add --context "SagaDbContext``2" Init  -v
            var contextFactory = new ContextFactory();

            using (SagaDbContext <SimpleSaga, SimpleSagaMap> context = contextFactory.CreateDbContext(Array.Empty <string>()))
            {
                context.Database.Migrate();
            }

            _sagaDbContextFactory = () => contextFactory.CreateDbContext(Array.Empty <string>());
            _sagaRepository       = new Lazy <ISagaRepository <SimpleSaga> >(() =>
                                                                             EntityFrameworkSagaRepository <SimpleSaga> .CreatePessimistic(_sagaDbContextFactory));
        }
        public Using_ef_connection_resiliency()
        {
            // add new migration by calling
            // dotnet ef migrations add --context "SagaDbContext``2" Init  -v
            var contextFactory = new ContextFactoryWithResilienceStrategy();

            using (var context = contextFactory.CreateDbContext(Array.Empty <string>()))
            {
                context.Database.Migrate();
            }

            _sagaDbContextFactory = () => contextFactory.CreateDbContext(Array.Empty <string>());
            _sagaRepository       = new Lazy <ISagaRepository <SimpleSaga> >(() =>
                                                                             EntityFrameworkSagaRepository <SimpleSaga> .CreatePessimistic(_sagaDbContextFactory));
        }
        public Using_custom_include_in_repository()
        {
            // add new migration by calling
            // dotnet ef migrations add --context "SagaWithDependencyContext" Init  -v
            var contextFactory = new SagaWithDependencyContextFactory();

            using (var context = contextFactory.CreateDbContext(Array.Empty <string>()))
            {
                context.Database.Migrate();
            }

            _sagaDbContextFactory = () => contextFactory.CreateDbContext(Array.Empty <string>());
            _sagaRepository       = new Lazy <ISagaRepository <SagaWithDependency> >(() =>
                                                                                     EntityFrameworkSagaRepository <SagaWithDependency> .CreatePessimistic(_sagaDbContextFactory,
                                                                                                                                                           queryCustomization: queryable =>
                                                                                                                                                           queryable.Include(it => it.Dependency).ThenInclude(dependency => dependency.SagaInnerDependency)
                                                                                                                                                           ));
        }
        protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
        {
            _discarded = GetTask <bool>();

            _simpleStateMachine = new SimpleStateMachine(x =>
            {
                _discarded.TrySetResult(true);
            });

            _sagaDbContextFactory = new DelegateSagaDbContextFactory <SimpleState>(() =>
                                                                                   new SimpleStateSagaDbContext(SagaDbContextFactoryProvider.GetLocalDbConnectionString()));

            _simpleStateRepository = new Lazy <ISagaRepository <SimpleState> >(() =>
                                                                               EntityFrameworkSagaRepository <SimpleState> .CreatePessimistic(_sagaDbContextFactory));


            configurator.StateMachineSaga(_simpleStateMachine, _simpleStateRepository.Value);

            base.ConfigureInMemoryReceiveEndpoint(configurator);
        }
Exemple #15
0
        public BatchStateMachineTests()
        {
            var dbOptionsBuilder = new DbContextOptionsBuilder()
                                   .UseSqlServer(TestConstants.ConnectionString)
                                   .EnableSensitiveDataLogging();

            _dbContextFactory = () => new SampleBatchDbContext(dbOptionsBuilder.Options);

            // Makes sure the DB is created for tests
            using (var db = _dbContextFactory())
            {
                db.Database.EnsureCreated();
            }

            _sagaRepository = EntityFrameworkSagaRepository <BatchState> .CreatePessimistic(_dbContextFactory, new CustomSqlLockStatementProvider("select * from {0}.{1} WITH (UPDLOCK, ROWLOCK) WHERE BatchId = @p0"));

            _stateMachine = new BatchStateMachine();

            _inMemoryTestHarness     = new InMemoryTestHarness();
            _inMemoryConsumerHarness = _inMemoryTestHarness.Consumer <FakeBatchJobSagaConsumer>(Guid.NewGuid().ToString());
            _inMemoryTestHarness.OnConfigureInMemoryReceiveEndpoint += ConfigureInMemoryReceiveEndpoint;
            _inMemoryTestHarness.OnConfigureInMemoryBus             += ConfigureInMemoryBus;
        }
Exemple #16
0
        static async Task Main(string[] args)
        {
            var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                cfg.Host(new Uri(BASE_URI), c =>
                {
                    c.Username("guest");
                    c.Password("guest");
                });

                cfg.ReceiveEndpoint("mysaga", ec =>
                {
                    ec.UseInMemoryOutbox();

                    var _mySagaInstance = new MySaga();
                    //ISagaRepository<MySaga> repoCreateQuoteSaga = new InMemorySagaRepository<MySaga>();

                    ISagaRepository <MySaga> repoCreateQuoteSaga = EntityFrameworkSagaRepository <MySaga> .CreatePessimistic(() =>
                    {
                        var options = new DbContextOptionsBuilder()
                                      .UseSqlServer(DB_CS, m =>
                        {
                            object p = m.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name);
                            m.MigrationsHistoryTable($"__MySaga");
                        })
                                      .Options;

                        var dbContext = new MySagaDbContext(options);
                        return(dbContext);
                    });
                    ec.Saga(repoCreateQuoteSaga);
                });
            });

            using var cancelation = new CancellationTokenSource(TimeSpan.FromSeconds(30));
            await bus.StartAsync(cancelation.Token);

            try
            {
                await Console.Out.WriteLineAsync("Press any key to exit...");

                await Task.Run(Console.ReadKey);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
            finally
            {
                try
                {
                    bus.Stop();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
Exemple #17
0
 ISagaRepository<ReadOnlyInstance> CreateSagaRepository()
 {
     return EntityFrameworkSagaRepository<ReadOnlyInstance>.CreatePessimistic(
         () => new ReadOnlySagaDbContextFactory().CreateDbContext(DbContextOptionsBuilder),
         RawSqlLockStatements);
 }