【问题标题】:ISagaDbContextFactory implementation for StructureMapStructureMap 的 ISagaDbContextFactory 实现
【发布时间】:2020-04-24 09:35:21
【问题描述】:

是否有用于 StructureMap 的 ISagaDbContextFactory 实现?我已经看到了 Autofac 的 AutofacSagaDbContextFactory 实现,我会为 StructureMap 编写自己的实现,但我不知道要寻找什么有效负载来获取 nested 的实例我希望masstransit 创建的strong> 容器?我尝试了以下没有运气

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 类解决了我的问题。

【问题讨论】:

    标签: entity-framework structuremap masstransit saga


    【解决方案1】:

    您没有指定您使用的 MassTransit 版本,但自 MassTransit 6.1 起,推荐的设置方法是使用容器集成包中的 AddDbContext 方法(在您的情况下应该是 MassTransit.StructureMap) .您可以在此处查看示例: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)}");
                    });
                });
            });
    });
    

    【讨论】:

    • 是的,新的集成是最好的方法。在 GitHub 存储库中使用了一个全容器上下文工厂。
    • 感谢@Chris Patterson,在查看了公共交通代码后,我确实发现了您所说的所有容器上下文工厂。现在按预期工作,非常感谢您
    猜你喜欢
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    相关资源
    最近更新 更多