ISagaDbContextFactory implementation for StructureMap

141 views Asked by At

Is there an implementation of ISagaDbContextFactory for StructureMap? I've seen an implementation of AutofacSagaDbContextFactory for Autofac, and I would write my own for StructureMap, but I don't know what payload to look for to get an instance of the nested container that I would have expected masstransit to have created?? I tried the following with no luck

public class StructureMapSagaDbContextFactory<TSaga> : ISagaDbContextFactory<TSaga> where TSaga : class, ISaga
{
  ...
  public DbContext CreateScoped<T>(ConsumeContext<T> context) where T : class
  {            
    if (context.TryGetPayload(out IContainer container)) // I don't know what to look for in the payload
      return currentScope.GetInstance<MyDbContext>();

    return Create();
  }
  ...
}

MyDbContext is registered as scoped with my container, and so would like a new instance per saga instance scope, i.e. similar to DbContext instance per web request if it were a web app, but for masstransit saga in this instance.

UPDATE: The ContainerSagaDbContextFactory class solved my problem.

1

There are 1 answers

2
nizmow On BEST ANSWER

You didn't specify which MassTransit version you were using, but the recommended way to set this up since MassTransit 6.1 is to use the AddDbContext method in the container integration package (which should be MassTransit.StructureMap in your case). You can see an example here: https://masstransit-project.com/usage/sagas/efcore.html#container-integration.

Snippet from that webpage:

services.AddMassTransit(cfg =>
{
    cfg.AddSagaStateMachine<OrderStateMachine, OrderState>()
        .EntityFrameworkRepository(r =>
        {
            r.ConcurrencyMode = ConcurrencyMode.Pessimistic; // or use Optimistic, which requires RowVersion

            r.AddDbContext<DbContext, OrderStateDbContext>((provider,builder) =>
            {
                builder.UseSqlServer(connectionString, m =>
                {
                    m.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name);
                    m.MigrationsHistoryTable($"__{nameof(OrderStateDbContext)}");
                });
            });
        });
});