StructureMap 的 ISagaDbContextFactory 实现

ISagaDbContextFactory implementation for StructureMap

是否有针对 StructureMap 的 ISagaDbContextFactory 实现?我已经看到 Autofac 的 AutofacSagaDbContextFactory 的实现,我会为 StructureMap 编写自己的实现,但我不知道要寻找什么有效负载来获取 nested 我本以为公共交通会创建的容器?我尝试了以下但没有成功

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 已注册为在我的容器范围内,因此希望每个 saga 实例范围有一个新实例,即如果它是一个 web 应用程序,则类似于每个 web 请求的 DbContext 实例,但在这个实例中用于 masstransit saga。

更新:ContainerSagaDbContextFactory class 解决了我的问题。

您没有指定您使用的是哪个 MassTransit 版本,但是从 MassTransit 6.1 开始推荐的设置方法是使用容器集成包中的 AddDbContext 方法(应该是 MassTransit.StructureMap in your case). You can see an example here: https://masstransit-project.com/usage/sagas/efcore.html#container-integration.

该网页的片段:

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)}");
                });
            });
        });
});